diff --git a/main.go b/main.go index 3c4ff7b..b5ad535 100644 --- a/main.go +++ b/main.go @@ -10,18 +10,22 @@ import ( func main() { + //日志第一优先级保障 + rest.LOGGER.Init() + defer rest.LOGGER.Destroy() + //将运行时参数装填到config中去。 rest.PrepareConfigs() + //全局运行的上下文 rest.CONTEXT.Init() defer rest.CONTEXT.Destroy() - + http.Handle("/", rest.CONTEXT.Router) dotPort := fmt.Sprintf(":%v", rest.CONFIG.ServerPort) - info := fmt.Sprintf("App started at http://localhost%v", dotPort) - rest.LogInfo(info) + rest.LOGGER.Info("App started at http://localhost:%v", rest.CONFIG.ServerPort) err1 := http.ListenAndServe(dotPort, nil) if err1 != nil { diff --git a/rest/alien_service.go b/rest/alien_service.go index d2eb389..b558d3e 100644 --- a/rest/alien_service.go +++ b/rest/alien_service.go @@ -1,9 +1,9 @@ package rest import ( + "fmt" "net/http" "time" - "fmt" ) //@Service @@ -20,6 +20,7 @@ type AlienService struct { //初始化方法 func (this *AlienService) Init() { + this.Bean.Init() //手动装填本实例的Bean. 这里必须要用中间变量方可。 b := CONTEXT.GetBean(this.matterDao) @@ -67,7 +68,7 @@ func (this *AlienService) PreviewOrDownload( operator *User, withContentDisposition bool) { - LogInfo("预览或下载文件 " + uuid + " " + filename) + this.logger.Info("预览或下载文件 " + uuid + " " + filename) matter := this.matterDao.CheckByUuid(uuid) diff --git a/rest/base_controller.go b/rest/base_controller.go index 75314cc..873f4dd 100644 --- a/rest/base_controller.go +++ b/rest/base_controller.go @@ -136,30 +136,30 @@ func (this *BaseController) findUser(writer http.ResponseWriter, request *http.R //验证用户是否已经登录。 sessionCookie, err := request.Cookie(COOKIE_AUTH_KEY) if err != nil { - LogInfo("获取用户cookie时出错啦") + this.logger.Warn("获取用户cookie信息失败啦~") return nil } sessionId := sessionCookie.Value - LogInfo("findUser sessionId = " + sessionId) + this.logger.Info("findUser sessionId = %s", sessionId) //去缓存中捞取看看 cacheItem, err := CONTEXT.SessionCache.Value(sessionId) if err != nil { - LogError("获取缓存时出错了" + err.Error()) + this.logger.Warn("获取缓存时出错了" + err.Error()) return nil } if cacheItem.Data() == nil { - LogError("cache item中已经不存在了 " + err.Error()) + this.logger.Warn("cache item中已经不存在了 " + err.Error()) return nil } if value, ok := cacheItem.Data().(*User); ok { return value } else { - LogError("cache item中的类型不是*User ") + this.logger.Error("cache item中的类型不是*User ") } return nil diff --git a/rest/bean.go b/rest/bean.go index 418ad45..f65f1b8 100644 --- a/rest/bean.go +++ b/rest/bean.go @@ -1,6 +1,8 @@ package rest -import "net/http" +import ( + "net/http" +) type IBean interface { Init() @@ -9,11 +11,11 @@ type IBean interface { } type Bean struct { - + logger *Logger } func (this *Bean) Init() { - + this.logger = LOGGER } //处理错误的统一方法 @@ -27,5 +29,3 @@ func (this *Bean) PanicError(err error) { func (this *Bean) PanicWebError(msg string, httpStatusCode int) { panic(&WebError{Msg: msg, Code: httpStatusCode}) } - -//处理日志的统一方法。 diff --git a/rest/config.go b/rest/config.go index 4091f4e..13e42dd 100644 --- a/rest/config.go +++ b/rest/config.go @@ -6,10 +6,10 @@ import ( "fmt" "github.com/json-iterator/go" "io/ioutil" - "time" - "unsafe" "os" "strconv" + "time" + "unsafe" ) const ( @@ -39,10 +39,6 @@ var ( //默认监听端口号 ServerPort: 6010, - //将日志输出到控制台。 - LogToConsole: true, - //日志的保存路径,如果没有指定,默认在根目录下的log文件夹中 - LogPath: "", //上传的文件路径,如果没有指定,默认在根目录下的matter文件夹中 MatterPath: "", //mysql相关配置。 @@ -71,12 +67,6 @@ var ( type Config struct { //默认监听端口号 ServerPort int - - //将日志输出到控制台。 - LogToConsole bool - - //日志的保存路径,要求不以/结尾。如果没有指定,默认在根目录下的log文件夹中。eg: /var/log/tank - LogPath string //上传的文件路径,要求不以/结尾。如果没有指定,默认在根目录下的matter文件夹中。eg: /var/www/matter MatterPath string @@ -106,27 +96,27 @@ type Config struct { func (this *Config) validate() { if this.ServerPort == 0 { - LogPanic("ServerPort 未配置") + LOGGER.Error("ServerPort 未配置") } if this.MysqlUsername == "" { - LogPanic("MysqlUsername 未配置") + LOGGER.Error("MysqlUsername 未配置") } if this.MysqlPassword == "" { - LogPanic("MysqlPassword 未配置") + LOGGER.Error("MysqlPassword 未配置") } if this.MysqlHost == "" { - LogPanic("MysqlHost 未配置") + LOGGER.Error("MysqlHost 未配置") } if this.MysqlPort == 0 { - LogPanic("MysqlPort 未配置") + LOGGER.Error("MysqlPort 未配置") } if this.MysqlSchema == "" { - LogPanic("MysqlSchema 未配置") + LOGGER.Error("MysqlSchema 未配置") } this.MysqlUrl = fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=utf8&parseTime=True&loc=Local", this.MysqlUsername, this.MysqlPassword, this.MysqlHost, this.MysqlPort, this.MysqlSchema) @@ -160,12 +150,12 @@ func LoadConfigFromFile() { filePath := GetConfPath() + "/tank.json" content, err := ioutil.ReadFile(filePath) if err != nil { - LogWarning(fmt.Sprintf("无法找到配置文件:%s,错误:%v\n将使用config.go中的默认配置项。", filePath, err)) + LOGGER.Warn(fmt.Sprintf("无法找到配置文件:%s,错误:%v\n将使用config.go中的默认配置项。", filePath, err)) } else { // 用 json.Unmarshal err := json.Unmarshal(content, CONFIG) if err != nil { - LogPanic("配置文件格式错误!") + LOGGER.Panic("配置文件格式错误!") } } @@ -180,15 +170,10 @@ func LoadConfigFromEnvironment() { if e == nil { CONFIG.ServerPort = i } else { - LogPanic(fmt.Sprintf("环境变量TANK_SERVER_PORT必须为整数!%v", tmpServerPort)) + LOGGER.Panic(fmt.Sprintf("环境变量TANK_SERVER_PORT必须为整数!%v", tmpServerPort)) } } - tmpLogPath := os.Getenv("TANK_LOG_PATH") - if tmpLogPath != "" { - CONFIG.LogPath = tmpLogPath - } - tmpMatterPath := os.Getenv("TANK_MATTER_PATH") if tmpMatterPath != "" { CONFIG.MatterPath = tmpMatterPath @@ -200,7 +185,7 @@ func LoadConfigFromEnvironment() { if e == nil { CONFIG.MysqlPort = i } else { - LogPanic(fmt.Sprintf("环境变量TANK_MYSQL_PORT必须为整数!%v", tmpMysqlPort)) + LOGGER.Panic(fmt.Sprintf("环境变量TANK_MYSQL_PORT必须为整数!%v", tmpMysqlPort)) } } @@ -242,11 +227,7 @@ func LoadConfigFromArguments() { //系统端口号 ServerPortPtr := flag.Int("ServerPort", CONFIG.ServerPort, "server port") - //系统端口号 - LogToConsolePtr := flag.Bool("LogToConsole", CONFIG.LogToConsole, "write log to console. for debug.") - //日志和上传文件的路径 - LogPathPtr := flag.String("LogPath", CONFIG.LogPath, "log path") MatterPathPtr := flag.String("MatterPath", CONFIG.MatterPath, "matter path") //mysql相关配置。 @@ -268,14 +249,6 @@ func LoadConfigFromArguments() { CONFIG.ServerPort = *ServerPortPtr } - if *LogToConsolePtr != CONFIG.LogToConsole { - CONFIG.LogToConsole = *LogToConsolePtr - } - - if *LogPathPtr != CONFIG.LogPath { - CONFIG.LogPath = *LogPathPtr - } - if *MatterPathPtr != CONFIG.MatterPath { CONFIG.MatterPath = *MatterPathPtr } @@ -326,11 +299,6 @@ func PrepareConfigs() { //第三级. 从程序参数中读取配置项 LoadConfigFromArguments() - //对于日志路径和文件路径还需要进行特殊处理 - if CONFIG.LogPath == "" { - CONFIG.LogPath = GetHomePath() + "/log" - } - MakeDirAll(CONFIG.LogPath) if CONFIG.MatterPath == "" { CONFIG.MatterPath = GetHomePath() + "/matter" } diff --git a/rest/context.go b/rest/context.go index de476fa..b2ae8a3 100644 --- a/rest/context.go +++ b/rest/context.go @@ -15,8 +15,6 @@ type Context struct { DB *gorm.DB //session缓存 SessionCache *CacheTable - //TODO:日志相关内容 - //各类的Bean Map。这里面是包含ControllerMap中所有元素 BeanMap map[string]IBean //只包含了Controller的map @@ -25,9 +23,8 @@ type Context struct { Router *Router } - //初始化上下文 -func (this *Context) Init() { +func (this *Context) Init() { //处理数据库连接的开关。 this.OpenDb() @@ -72,7 +69,6 @@ func (this *Context) CloseDb() { } } - //注册一个Bean func (this *Context) registerBean(bean IBean) { @@ -83,7 +79,7 @@ func (this *Context) registerBean(bean IBean) { err := fmt.Sprintf("【%s】已经被注册了,跳过。", typeName) if _, ok := this.BeanMap[typeName]; ok { - LogError(fmt.Sprintf(err)) + LOGGER.Error(fmt.Sprintf(err)) } else { this.BeanMap[typeName] = element @@ -170,5 +166,4 @@ func (this *Context) initBeans() { //销毁的方法 func (this *Context) Destroy() { this.CloseDb() - } diff --git a/rest/footprint_service.go b/rest/footprint_service.go index d071fb0..5c319a7 100644 --- a/rest/footprint_service.go +++ b/rest/footprint_service.go @@ -15,6 +15,7 @@ type FootprintService struct { //初始化方法 func (this *FootprintService) Init() { + this.Bean.Init() //手动装填本实例的Bean. 这里必须要用中间变量方可。 b := CONTEXT.GetBean(this.footprintDao) diff --git a/rest/image_cache_dao.go b/rest/image_cache_dao.go index 9ff6160..41e4781 100644 --- a/rest/image_cache_dao.go +++ b/rest/image_cache_dao.go @@ -149,13 +149,13 @@ func (this *ImageCacheDao) deleteFileAndDir(imageCache *ImageCache) { //删除文件 err := os.Remove(filePath) if err != nil { - LogError(fmt.Sprintf("删除磁盘上的文件%s出错,不做任何处理 %s", filePath, err.Error())) + this.logger.Error(fmt.Sprintf("删除磁盘上的文件%s出错,不做任何处理 %s", filePath, err.Error())) } //删除这一层文件夹 err = os.Remove(dirPath) if err != nil { - LogError(fmt.Sprintf("删除磁盘上的文件夹%s出错,不做任何处理 %s", dirPath, err.Error())) + this.logger.Error(fmt.Sprintf("删除磁盘上的文件夹%s出错,不做任何处理 %s", dirPath, err.Error())) } } diff --git a/rest/image_cache_service.go b/rest/image_cache_service.go index 5153495..e77b337 100644 --- a/rest/image_cache_service.go +++ b/rest/image_cache_service.go @@ -19,6 +19,7 @@ type ImageCacheService struct { //初始化方法 func (this *ImageCacheService) Init() { + this.Bean.Init() //手动装填本实例的Bean. 这里必须要用中间变量方可。 b := CONTEXT.GetBean(this.imageCacheDao) diff --git a/rest/install.go b/rest/install.go index 1910764..ce85427 100644 --- a/rest/install.go +++ b/rest/install.go @@ -13,7 +13,7 @@ func InstallDatabase() { db, err := gorm.Open("mysql", CONFIG.MysqlUrl) if err != nil { - LogPanic(fmt.Sprintf("无法打开%s", CONFIG.MysqlUrl)) + LOGGER.Panic(fmt.Sprintf("无法打开%s", CONFIG.MysqlUrl)) } if db != nil { defer db.Close() @@ -28,9 +28,9 @@ func InstallDatabase() { createDownloadToken := "CREATE TABLE `tank20_download_token` (`uuid` char(36) NOT NULL,`user_uuid` char(36) DEFAULT NULL COMMENT '用户uuid',`matter_uuid` char(36) DEFAULT NULL COMMENT '文件标识',`expire_time` timestamp NULL DEFAULT NULL COMMENT '授权访问的次数',`ip` varchar(45) DEFAULT NULL COMMENT '消费者的ip',`sort` bigint(20) DEFAULT NULL,`modify_time` timestamp NULL DEFAULT NULL,`create_time` timestamp NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',PRIMARY KEY (`uuid`),UNIQUE KEY `id_UNIQUE` (`uuid`)) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='下载的token表';" db = db.Exec(createDownloadToken) if db.Error != nil { - LogPanic(db.Error) + LOGGER.Panic(db.Error.Error()) } - LogInfo("创建DownloadToken表") + LOGGER.Info("创建DownloadToken表") } @@ -40,9 +40,9 @@ func InstallDatabase() { createMatter := "CREATE TABLE `tank20_matter` (`uuid` char(36) NOT NULL,`puuid` varchar(45) DEFAULT NULL COMMENT '上一级的uuid',`user_uuid` char(36) DEFAULT NULL COMMENT '上传的用户id',`dir` tinyint(1) DEFAULT '0' COMMENT '是否是文件夹',`alien` tinyint(1) DEFAULT '0',`name` varchar(255) DEFAULT NULL COMMENT '文件名称',`md5` varchar(45) DEFAULT NULL COMMENT '文件的md5值',`size` bigint(20) DEFAULT '0' COMMENT '文件大小',`privacy` tinyint(1) DEFAULT '0' COMMENT '文件是否是公有的',`path` varchar(255) DEFAULT NULL,`sort` bigint(20) DEFAULT NULL,`modify_time` timestamp NULL DEFAULT NULL,`create_time` timestamp NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',PRIMARY KEY (`uuid`),UNIQUE KEY `id_UNIQUE` (`uuid`)) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='file表';" db = db.Exec(createMatter) if db.Error != nil { - LogPanic(db.Error) + LOGGER.Panic(db.Error.Error()) } - LogInfo("创建Matter表") + LOGGER.Info("创建Matter表") } @@ -52,9 +52,9 @@ func InstallDatabase() { createPreference := "CREATE TABLE `tank20_preference` (`uuid` char(36) NOT NULL,`name` varchar(45) DEFAULT NULL COMMENT '网站名称',`logo_url` varchar(255) DEFAULT NULL,`favicon_url` varchar(255) DEFAULT NULL,`footer_line1` varchar(1024) DEFAULT NULL,`footer_line2` varchar(1024) DEFAULT NULL,`version` varchar(45) DEFAULT NULL,`sort` bigint(20) DEFAULT NULL,`modify_time` timestamp NULL DEFAULT NULL,`create_time` timestamp NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',PRIMARY KEY (`uuid`),UNIQUE KEY `id_UNIQUE` (`uuid`)) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='网站偏好设置表';" db = db.Exec(createPreference) if db.Error != nil { - LogPanic(db.Error) + LOGGER.Panic(db.Error.Error()) } - LogInfo("创建Preference表") + LOGGER.Info("创建Preference表") } session := &Session{} @@ -64,9 +64,9 @@ func InstallDatabase() { createSession := "CREATE TABLE `tank20_session` (`uuid` char(36) NOT NULL,`authentication` char(36) DEFAULT NULL COMMENT '认证身份,存放在cookie中',`user_uuid` char(36) DEFAULT NULL COMMENT '用户uuid',`ip` varchar(45) DEFAULT NULL COMMENT '用户的ip地址',`expire_time` timestamp NULL DEFAULT NULL,`sort` bigint(20) DEFAULT NULL,`modify_time` timestamp NULL DEFAULT NULL,`create_time` timestamp NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',PRIMARY KEY (`uuid`),UNIQUE KEY `id_UNIQUE` (`uuid`)) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='session表';" db = db.Exec(createSession) if db.Error != nil { - LogPanic(db.Error) + LOGGER.Panic(db.Error.Error()) } - LogInfo("创建Session表") + LOGGER.Info("创建Session表") } uploadToken := &UploadToken{} @@ -76,9 +76,9 @@ func InstallDatabase() { createUploadToken := "CREATE TABLE `tank20_upload_token` (`uuid` char(36) NOT NULL,`user_uuid` char(36) DEFAULT NULL COMMENT '用户uuid',`folder_uuid` char(36) DEFAULT NULL,`matter_uuid` char(36) DEFAULT NULL,`filename` varchar(255) DEFAULT NULL COMMENT '文件后缀名的过滤,可以只允许用户上传特定格式的文件。',`privacy` tinyint(1) DEFAULT '1',`size` bigint(20) DEFAULT '0',`expire_time` timestamp NULL DEFAULT NULL,`ip` varchar(45) DEFAULT NULL COMMENT '消费者的ip',`sort` bigint(20) DEFAULT NULL,`modify_time` timestamp NULL DEFAULT NULL,`create_time` timestamp NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',PRIMARY KEY (`uuid`),UNIQUE KEY `id_UNIQUE` (`uuid`)) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='上传的token表';" db = db.Exec(createUploadToken) if db.Error != nil { - LogPanic(db.Error) + LOGGER.Panic(db.Error.Error()) } - LogInfo("创建UploadToken表") + LOGGER.Info("创建UploadToken表") } user := &User{} @@ -87,23 +87,23 @@ func InstallDatabase() { //验证超级管理员的信息 if m, _ := regexp.MatchString(`^[0-9a-zA-Z_]+$`, CONFIG.AdminUsername); !m { - LogPanic(`超级管理员用户名必填,且只能包含字母,数字和'_''`) + LOGGER.Panic(`超级管理员用户名必填,且只能包含字母,数字和'_''`) } if len(CONFIG.AdminPassword) < 6 { - LogPanic(`超级管理员密码长度至少为6位`) + LOGGER.Panic(`超级管理员密码长度至少为6位`) } if CONFIG.AdminEmail == "" { - LogPanic("超级管理员邮箱必填!") + LOGGER.Panic("超级管理员邮箱必填!") } createUser := "CREATE TABLE `tank20_user` (`uuid` char(36) NOT NULL,`role` varchar(45) DEFAULT 'USER',`username` varchar(255) DEFAULT NULL COMMENT '昵称',`password` varchar(255) DEFAULT NULL COMMENT '密码',`email` varchar(45) DEFAULT NULL COMMENT '邮箱',`phone` varchar(45) DEFAULT NULL COMMENT '电话',`gender` varchar(45) DEFAULT 'UNKNOWN' COMMENT '性别,默认未知',`city` varchar(45) DEFAULT NULL COMMENT '城市',`avatar_url` varchar(255) DEFAULT NULL COMMENT '头像链接',`last_time` datetime DEFAULT NULL COMMENT '上次登录使劲按',`last_ip` varchar(45) DEFAULT NULL,`size_limit` int(11) DEFAULT '-1' COMMENT '该账号上传文件的大小限制,单位byte。<0 表示不设限制',`status` varchar(45) DEFAULT 'OK',`sort` bigint(20) DEFAULT NULL,`modify_time` timestamp NULL DEFAULT NULL,`create_time` timestamp NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',PRIMARY KEY (`uuid`),UNIQUE KEY `id_UNIQUE` (`uuid`)) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='用户表描述';" db = db.Exec(createUser) if db.Error != nil { - LogPanic(db.Error) + LOGGER.Panic(db.Error.Error()) } - LogInfo("创建User表") + LOGGER.Info("创建User表") user := &User{} timeUUID, _ := uuid.NewV4() diff --git a/rest/logger.go b/rest/logger.go new file mode 100644 index 0000000..c645925 --- /dev/null +++ b/rest/logger.go @@ -0,0 +1,73 @@ +package rest + +import ( + "fmt" + "log" + "os" +) + +//日志系统必须高保 +//全局唯一的日志对象(在main函数中初始化) +var LOGGER *Logger = &Logger{} + +//在Logger的基础上包装一个全新的Logger. +type Logger struct { + //继承logger + goLogger *log.Logger + //日志记录所在的文件 + file *os.File +} + +//处理日志的统一方法。 +func (this *Logger) log(prefix string, format string, v ...interface{}) { + fmt.Printf(format+"\r\n", v...) + + this.goLogger.SetPrefix(prefix) + this.goLogger.Printf(format, v...) +} + +//处理日志的统一方法。 +func (this *Logger) Debug(format string, v ...interface{}) { + this.log("[debug]", format, v...) +} + +func (this *Logger) Info(format string, v ...interface{}) { + this.log("[info]", format, v...) +} + +func (this *Logger) Warn(format string, v ...interface{}) { + this.log("[warn]", format, v...) +} + +func (this *Logger) Error(format string, v ...interface{}) { + this.log("[error]", format, v...) +} + +func (this *Logger) Panic(format string, v ...interface{}) { + this.log("[panic]", format, v...) + panic(fmt.Sprintf(format, v...)) +} + +func (this *Logger) Init() { + + //日志输出到文件中 文件打开后暂时不关闭 + filePath := GetLogPath() + "/tank.log" + fmt.Printf("使用日志文件 %s\r\n", filePath) + f, err := os.OpenFile(filePath, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666) + if err != nil { + panic("日志文件无法正常打开: " + err.Error()) + } + + this.goLogger = log.New(f, "", log.Ltime) + this.file = f +} + +func (this *Logger) Destroy() { + if this.file != nil { + err := this.file.Close() + if err != nil { + panic("尝试关闭日志时出错: " + err.Error()) + } + } + +} diff --git a/rest/matter_dao.go b/rest/matter_dao.go index ad463c1..7721638 100644 --- a/rest/matter_dao.go +++ b/rest/matter_dao.go @@ -247,13 +247,13 @@ func (this *MatterDao) Delete(matter *Matter) { //删除文件 err := os.Remove(filePath) if err != nil { - LogError(fmt.Sprintf("删除磁盘上的文件出错,不做任何处理 %s", err.Error())) + this.logger.Error(fmt.Sprintf("删除磁盘上的文件出错,不做任何处理 %s", err.Error())) } //删除这一层文件夹 err = os.Remove(dirPath) if err != nil { - LogError(fmt.Sprintf("删除磁盘上的文件夹出错,不做任何处理 %s", err.Error())) + this.logger.Error(fmt.Sprintf("删除磁盘上的文件夹出错,不做任何处理 %s", err.Error())) } } diff --git a/rest/matter_service.go b/rest/matter_service.go index 32de8da..85f8ac7 100644 --- a/rest/matter_service.go +++ b/rest/matter_service.go @@ -24,6 +24,7 @@ type MatterService struct { //初始化方法 func (this *MatterService) Init() { + this.Bean.Init() //手动装填本实例的Bean. 这里必须要用中间变量方可。 b := CONTEXT.GetBean(this.matterDao) diff --git a/rest/preference_service.go b/rest/preference_service.go index beeb41d..3fa6914 100644 --- a/rest/preference_service.go +++ b/rest/preference_service.go @@ -8,6 +8,7 @@ type PreferenceService struct { //初始化方法 func (this *PreferenceService) Init() { + this.Bean.Init() //手动装填本实例的Bean. 这里必须要用中间变量方可。 b := CONTEXT.GetBean(this.preferenceDao) diff --git a/rest/router.go b/rest/router.go index 5ffa6af..eeac4da 100644 --- a/rest/router.go +++ b/rest/router.go @@ -12,8 +12,8 @@ import ( //用于处理所有前来的请求 type Router struct { footprintService *FootprintService - userService *UserService - routeMap map[string]func(writer http.ResponseWriter, request *http.Request) + userService *UserService + routeMap map[string]func(writer http.ResponseWriter, request *http.Request) } //构造方法 @@ -49,7 +49,7 @@ func NewRouter() *Router { func (this *Router) GlobalPanicHandler(writer http.ResponseWriter, request *http.Request) { if err := recover(); err != nil { - LogError(fmt.Sprintf("全局异常: %v", err)) + LOGGER.Error(fmt.Sprintf("全局异常: %v", err)) var webResult *WebResult = nil if value, ok := err.(string); ok { diff --git a/rest/user_controller.go b/rest/user_controller.go index 1fd0c57..041cf70 100644 --- a/rest/user_controller.go +++ b/rest/user_controller.go @@ -215,7 +215,7 @@ func (this *UserController) Logout(writer http.ResponseWriter, request *http.Req //session置为过期 sessionCookie, err := request.Cookie(COOKIE_AUTH_KEY) if err != nil { - LogError("找不到任何登录信息") + this.logger.Error("找不到任何登录信息") return this.Success("已经退出登录了!") } sessionId := sessionCookie.Value @@ -230,7 +230,7 @@ func (this *UserController) Logout(writer http.ResponseWriter, request *http.Req //删掉session缓存 _, err = CONTEXT.SessionCache.Delete(sessionId) if err != nil { - LogError("删除用户session缓存时出错") + this.logger.Error("删除用户session缓存时出错") } //清空客户端的cookie. diff --git a/rest/user_service.go b/rest/user_service.go index cb1ba72..8a1ef6b 100644 --- a/rest/user_service.go +++ b/rest/user_service.go @@ -14,6 +14,7 @@ type UserService struct { //初始化方法 func (this *UserService) Init() { + this.Bean.Init() //手动装填本实例的Bean. 这里必须要用中间变量方可。 b := CONTEXT.GetBean(this.userDao) @@ -37,18 +38,18 @@ func (this *UserService) bootstrap(writer http.ResponseWriter, request *http.Req //验证用户是否已经登录。 sessionCookie, err := request.Cookie(COOKIE_AUTH_KEY) if err != nil { - LogError("找不到任何登录信息") + this.logger.Error("找不到任何登录信息") return } sessionId := sessionCookie.Value - LogInfo("请求的sessionId = " + sessionId) + this.logger.Info("请求的sessionId = " + sessionId) //去缓存中捞取 cacheItem, err := CONTEXT.SessionCache.Value(sessionId) if err != nil { - LogError("获取缓存时出错了" + err.Error()) + this.logger.Error("获取缓存时出错了" + err.Error()) } //缓存中没有,尝试去数据库捞取 @@ -57,7 +58,7 @@ func (this *UserService) bootstrap(writer http.ResponseWriter, request *http.Req if session != nil { duration := session.ExpireTime.Sub(time.Now()) if duration <= 0 { - LogError("登录信息已过期") + this.logger.Error("登录信息已过期") } else { user := this.userDao.FindByUuid(session.UserUuid) if user != nil { @@ -65,7 +66,7 @@ func (this *UserService) bootstrap(writer http.ResponseWriter, request *http.Req CONTEXT.SessionCache.Add(sessionCookie.Value, duration, user) } else { - LogError("没有找到对应的user " + session.UserUuid) + this.logger.Error("没有找到对应的user " + session.UserUuid) } } } diff --git a/rest/util_log.go b/rest/util_log.go deleted file mode 100644 index 040fb32..0000000 --- a/rest/util_log.go +++ /dev/null @@ -1,50 +0,0 @@ -package rest - -import ( - "fmt" - "log" - "os" - "time" -) - -func Log(prefix string, content string) { - - //日志输出到文件中 - filePath := CONFIG.LogPath + "/tank-" + time.Now().Local().Format("2006-01-02") + ".log" - f, err := os.OpenFile(filePath, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666) - if err != nil { - fmt.Errorf("error opening file: %v", err) - } - defer f.Close() - - log.SetOutput(f) - log.SetPrefix(prefix) - log.Println(content) - - //如果需要输出到控制台。 - if CONFIG.LogToConsole { - fmt.Println(content) - } - -} - -func LogDebug(content string) { - go Log("[Debug]", content) -} - -func LogInfo(content string) { - go Log("[Info]", content) -} - -func LogWarning(content string) { - go Log("[Warning]", content) -} - -func LogError(content string) { - go Log("[Error]", content) -} - -func LogPanic(content interface{}) { - Log("[Panic]", fmt.Sprintf("%v", content)) - panic(content) -} diff --git a/rest/util_path.go b/rest/util_path.go index 6fa271f..5fe07c2 100644 --- a/rest/util_path.go +++ b/rest/util_path.go @@ -87,6 +87,26 @@ func GetConfPath() string { return filePath } +//获取日志的路径 +//例如:默认存放于 home/log +func GetLogPath() string { + + homePath := GetHomePath() + filePath := homePath + "/log" + exists, err := PathExists(filePath) + if err != nil { + panic("判断日志文件夹是否存在时出错!") + } + if !exists { + err = os.MkdirAll(filePath, 0777) + if err != nil { + panic("创建日志文件夹时出错!") + } + } + + return filePath +} + //获取某个用户文件应该存放的位置。这个是相对GetFilePath的路径 //例如:/zicla/2006-01-02/1510122428000 func GetUserFilePath(username string, cache bool) (string, string) {