From bb2311148ec05d998c2b7043c8905658e2602d65 Mon Sep 17 00:00:00 2001 From: hoteas <925970985@qq.com> Date: Sat, 22 Feb 2020 00:13:41 +0800 Subject: [PATCH] =?UTF-8?q?=E5=A2=9E=E5=8A=A0log=E6=96=87=E4=BB=B6?= =?UTF-8?q?=E5=AD=98=E5=8F=96=EF=BC=8C=E4=BB=A5=E5=8F=8A=E5=A2=9E=E5=8A=A0?= =?UTF-8?q?LOG=E5=87=BD=E6=95=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .idea/workspace.xml | 47 +++++++++++++++++++++-- application.go | 41 ++++++++------------ const.go | 12 ++++-- context.go | 2 +- error.go | 25 +++---------- example/config/config.json | 30 --------------- example/config/confignote.json | 34 ----------------- example/main.go | 3 +- func.go | 68 ++++++++++++++++++++++++++++++++++ var.go | 9 +++-- 10 files changed, 148 insertions(+), 123 deletions(-) delete mode 100644 example/config/config.json delete mode 100644 example/config/confignote.json diff --git a/.idea/workspace.xml b/.idea/workspace.xml index 04bbe8b..00f7b55 100644 --- a/.idea/workspace.xml +++ b/.idea/workspace.xml @@ -1,7 +1,18 @@ - + + + + + + + + + + + + @@ -158,6 +187,18 @@ - + + + + + file://$PROJECT_DIR$/func.go + 49 + + + \ No newline at end of file diff --git a/application.go b/application.go index e66e43d..4633806 100644 --- a/application.go +++ b/application.go @@ -4,17 +4,13 @@ import ( "bytes" "database/sql" "encoding/json" - "errors" - "fmt" "io/ioutil" - "log" "net/http" "net/url" "os" "path/filepath" "strconv" "strings" - "time" ) type Application struct { @@ -106,8 +102,9 @@ func (this *Application) Run(router Router) { //异常处理 defer func() { if err := recover(); err != nil { - this.SetError(errors.New(fmt.Sprint(err)), LOG_FMT) - //log.Println(err) + //this.SetError(errors.New(fmt.Sprint(err)), LOG_FMT) + logFmt(err, 2, LOG_ERROR) + this.Run(router) } }() @@ -126,7 +123,7 @@ func (this *Application) Run(router Router) { //启动服务 this.Server.Addr = ":" + this.Port err := this.Server.ListenAndServe() - log.Println(err) + logFmt(err, 2) ch <- 1 }() @@ -138,19 +135,19 @@ func (this *Application) Run(router Router) { //启动服务 this.Server.Addr = ":" + this.TLSPort err := this.Server.ListenAndServeTLS(this.Config.GetString("tlsCert"), this.Config.GetString("tlsKey")) - log.Println(err) + logFmt(err, 2) ch <- 2 }() } else { - log.Println("没有端口启用") + logFmt("没有端口启用", 2, LOG_INFO) return } value := <-ch - log.Println("启动服务失败 : ", value) + logFmt("启动服务失败 : "+ObjToStr(value), 2, LOG_ERROR) } //启动实例 @@ -217,11 +214,11 @@ func (this *Application) SetConfig(configPath ...string) { cmap.JsonToMap(string(btes), &this.Error) for k, v := range cmap { - this.Config.Put(k, v) //程序配置 - Config.Put(k, v) //系统配置 + this.Config[k] = v //程序配置 + Config[k] = v //系统配置 } } else { - log.Println("配置文件不存在,或者配置出错,使用缺省默认配置") + logFmt("配置文件不存在,或者配置出错,使用缺省默认配置", 2) } @@ -238,21 +235,13 @@ func (this *Application) SetConfig(configPath ...string) { //写入配置说明 var configNoteByte bytes.Buffer json.Indent(&configNoteByte, []byte(ConfigNote.ToJsonString()), "", "\t") - ioutil.WriteFile(filepath.Dir(this.configPath)+"/confignote.json", configNoteByte.Bytes(), os.ModeAppend) - //写入配置 + + os.MkdirAll(filepath.Dir(this.configPath), os.ModeDir) err = ioutil.WriteFile(this.configPath, configByte.Bytes(), os.ModeAppend) if err != nil { - os.MkdirAll(filepath.Dir(this.configPath), os.ModeDir) - os.Create(this.configPath) - err = ioutil.WriteFile(this.configPath, configByte.Bytes(), os.ModeAppend) - if err != nil { - this.Error.SetError(err) - } - //写入配置说明 - os.Create(filepath.Dir(this.configPath) + "/confignote.json") - ioutil.WriteFile(filepath.Dir(this.configPath)+"/confignote.json", configNoteByte.Bytes(), os.ModeAppend) - + this.Error.SetError(err) } + ioutil.WriteFile(filepath.Dir(this.configPath)+"/confignote.json", configNoteByte.Bytes(), os.ModeAppend) } @@ -338,7 +327,7 @@ func (this *Application) handler(w http.ResponseWriter, req *http.Request) { this.crossDomain(&context) //是否展示日志 if this.Config.GetInt("connectLogShow") != 0 { - log.Println(context.HandlerStr + time.Now().Format(" 2006-01-02 15:04 ") + Substr(context.Req.RemoteAddr, 0, strings.Index(context.Req.RemoteAddr, ":"))) + logFmt(Substr(context.Req.RemoteAddr, 0, strings.Index(context.Req.RemoteAddr, ":"))+" "+context.HandlerStr, 0, LOG_INFO) } //访问拦截true继续false暂停 diff --git a/const.go b/const.go index cff7b89..8910835 100644 --- a/const.go +++ b/const.go @@ -1,9 +1,15 @@ package hotime +type LOG_MODE int + const ( - LOG_FMT = 0 - LOG_NIL = 1 - LOG_FILE = 2 + LOG_NIL = 0 + LOG_FMT = 1 + //LOG_FILE = 2 + + LOG_INFO LOG_MODE = 0 + LOG_WARN LOG_MODE = 1 + LOG_ERROR LOG_MODE = 2 ) //session储存头 diff --git a/context.go b/context.go index a393441..27b5d64 100644 --- a/context.go +++ b/context.go @@ -37,7 +37,7 @@ func (this *Context) Display(statu int, data interface{}) { tpe := this.Config.GetMap("error").GetString(ObjToStr(statu)) if tpe == "" { - this.SetError(errors.New("找不到对应的错误码")) + logFmt(errors.New("找不到对应的错误码"), 2, LOG_WARN) } temp["type"] = tpe diff --git a/error.go b/error.go index fcedb1e..323f8f3 100644 --- a/error.go +++ b/error.go @@ -1,40 +1,25 @@ package hotime -import ( - "log" -) - //框架层处理错误 type Error struct { + error err error } func (this *Error) GetError() error { - return this.err + return this.error } func (this *Error) SetError(err error, loglevel ...int) { - this.err = nil + this.error = nil if err == nil { + this.error = err this.err = err return } - - lev := Config.GetInt("logLevel") - - if len(loglevel) != 0 { - lev = loglevel[0] - } - - if lev == LOG_FMT { - log.Println(err) - } - if lev == LOG_FILE { - log.Println(err) - } - this.err = err + this.error = err return } diff --git a/example/config/config.json b/example/config/config.json deleted file mode 100644 index 8eb4714..0000000 --- a/example/config/config.json +++ /dev/null @@ -1,30 +0,0 @@ -{ - "cacheLongTime": 2592000, - "cacheShortTime": 7200, - "dbCached": 0, - "dbHost": "127.0.0.1", - "dbName": "test", - "dbPort": "3306", - "dbPwd": "root", - "dbUser": "root", - "debug": 1, - "defFile": [ - "index.html", - "index.htm" - ], - "error": { - "1": "内部系统异常", - "2": "访问权限异常", - "3": "请求参数异常", - "4": "数据处理异常", - "5": "数据结果异常" - }, - "logLevel": 1, - "modeRouterStrict": false, - "port": "0", - "sessionName": "HOTIME", - "tlsCert": "", - "tlsKey": "", - "tlsPort": "0", - "tpt": "tpt" -} \ No newline at end of file diff --git a/example/config/confignote.json b/example/config/confignote.json deleted file mode 100644 index baa64db..0000000 --- a/example/config/confignote.json +++ /dev/null @@ -1,34 +0,0 @@ -{ - "cacheLongTime": "两级缓存,长缓存存储时间60 * 60 * 24 * 30,一般为数据库或者redis缓存", - "cacheShortTime": "两级缓存,短缓存存储时间60 * 60 * 2,一般为内存缓存", - "connectLogShow": "如果需要web访问链接、访问ip、访问时间打印,0为关闭其他数字开启此功能", - "crossDomain": "如果需要跨域设置,空字符串为不开启,*为开启所有网站允许跨域,http://www.baidu.com为指定域允许跨域", - "dbCached": "是否开启数据库缓存0为关闭,其他开启", - "dbHost": "数据库ip地址默认127.0.0.1", - "dbName": "数据库名称,sqlite为文件路径比如a/x.db", - "dbPort": "数据库端口", - "dbPwd": "数据库密码", - "dbType": "如果需要使用自动数据库配置,请设置此项,手动配置数据库不需要,目前支持mysql,sqlite", - "dbUser": "数据库用户名", - "debug": "是否开启debug模式,0关闭,其他开启,debug模式下日志展示更全", - "defFile": "默认访问文件,默认访问index.html或者index.htm文件", - "error": { - "1": "内部系统异常,在环境配置,文件访问权限等基础运行环境条件不足造成严重错误时使用", - "2": "访问权限异常,没有登录或者登录异常等时候使用", - "3": "请求参数异常,request参数不满足要求,比如参数不足,参数类型错误,参数不满足要求等时候使用", - "4": "数据处理异常,数据库操作或者三方请求返回的结果非正常结果,比如数据库突然中断等时候使用", - "5": "数据结果异常,一般用于无法给出response要求的格式要求下使用,比如response需要的是string格式但你只能提供int数据时", - "注释": "web服务内置错误提示,自定义异常建议10开始" - }, - "logLevel": "日志等级,0打印,1关闭,2,记录到文件", - "modeRouterStrict": "路由严格模式false,为大小写忽略必须匹配,true必须大小写匹配", - "port": "web服务开启Http端口,0为不启用http服务", - "redisHost": "如果需要使用redis服务时配置,默认服务ip:127.0.0.1", - "redisPort": "如果需要使用redis服务时配置,默认服务端口:6379", - "redisPwd": "如果需要使用redis服务时配置,默认服务密码:123456", - "sessionName": "设置session的cookie名默认HOTIME", - "tlsCert": "https证书", - "tlsKey": "https密钥", - "tlsPort": "web服务https端口,0为不启用https服务", - "tpt": "静态文件目录,默认为程序目录下tpt目录" -} \ No newline at end of file diff --git a/example/main.go b/example/main.go index 8dd7006..c5cb4f3 100644 --- a/example/main.go +++ b/example/main.go @@ -4,7 +4,6 @@ import ( "code.hoteas.com/hoteas/hotime" "code.hoteas.com/hoteas/hotime/tools/db" "fmt" - "strings" //"go.hoteas.com/hotime/cache" "golang.org/x/net/websocket" "time" @@ -16,7 +15,7 @@ func main() { appIns := hotime.Application{} appIns.SetConnectListener(func(context *hotime.Context) bool { - fmt.Println(context.HandlerStr + time.Now().Format(" 2006-01-02 15:04 ") + hotime.Substr(context.Req.RemoteAddr, 0, strings.Index(context.Req.RemoteAddr, ":"))) + //fmt.Println(context.HandlerStr + time.Now().Format(" 2006-01-02 15:04 ") + hotime.Substr(context.Req.RemoteAddr, 0, strings.Index(context.Req.RemoteAddr, ":"))) //this.HandlerStr = "/test.html" return true diff --git a/func.go b/func.go index 5b7f1b7..9e4efad 100644 --- a/func.go +++ b/func.go @@ -3,8 +3,13 @@ package hotime import ( "crypto/md5" "encoding/hex" + "fmt" "math" + "os" + "path/filepath" + "runtime" "strings" + "time" ) //安全锁 @@ -24,6 +29,69 @@ import ( // return res //} +func LogFmt(logMsg interface{}, loglevel ...LOG_MODE) { + + logFmt(logMsg, 2, loglevel...) +} + +//日志打印以及存储到文件 +func logFmt(logMsg interface{}, printLevel int, loglevel ...LOG_MODE) { + + if Config.GetInt("logLevel") == int(LOG_NIL) { + return + } + + lev := LOG_INFO + if len(loglevel) != 0 { + lev = loglevel[0] + } + gofile := "" + + if Config.GetInt("debug") != 0 && printLevel != 0 { + _, file, line, ok := runtime.Caller(printLevel) + if ok { + gofile = " " + file + ":" + ObjToStr(line) + } + } + + logStr := "" + + if lev == LOG_INFO { + logStr = "info:" + } + if printLevel == 0 { + logStr = "connect:" + } + + if lev == LOG_WARN { + logStr = "warn:" + } + + if lev == LOG_ERROR { + logStr = "error:" + } + + logStr = fmt.Sprintln(time.Now().Format("2006/01/02 15:04:05"), logStr, logMsg, gofile) + //打印日志 + fmt.Print(logStr) + //不需要存储到文件 + if Config.GetString("logFile") == "" { + return + } + //存储到文件 + logFilePath := time.Now().Format(Config.GetString("logFile")) + + os.MkdirAll(filepath.Dir(logFilePath), os.ModeAppend) + //os.Create(logFilePath) + f, err := os.OpenFile(logFilePath, os.O_APPEND|os.O_CREATE, 0644) + if err != nil { + return + } + f.Write([]byte(logStr)) + f.Close() + +} + //字符串首字符大写 func StrFirstToUpper(str string) string { if len(str) == 0 { diff --git a/var.go b/var.go index 4337706..5a249b3 100644 --- a/var.go +++ b/var.go @@ -7,7 +7,7 @@ var App = map[string]*Application{} //整个项目 var Config = Map{ "debug": 1, //debug 0关闭1开启 - "logLevel": LOG_NIL, + "logLevel": LOG_FMT, "dbHost": "127.0.0.1", "dbName": "test", "dbUser": "root", @@ -26,7 +26,7 @@ var Config = Map{ "tpt": "tpt", "defFile": []string{"index.html", "index.htm"}, "modeRouterStrict": false, //路由严格模式/a/b/c - "port": "0", + "port": "80", "sessionName": "HOTIME", "tlsPort": "0", "tlsKey": "", @@ -34,7 +34,8 @@ var Config = Map{ } var ConfigNote = Map{ - "logLevel": "日志等级,0打印,1关闭,2,记录到文件", + "logLevel": "日志等级,0关闭,1打印", + "logFile": "如果需要存储日志文件时使用,保存格式为:a/b/c/20060102150405.txt,将生成:a/b/c/年月日时分秒.txt,按需设置", "debug": "是否开启debug模式,0关闭,其他开启,debug模式下日志展示更全", //debug 0关闭1开启 "dbHost": "数据库ip地址默认127.0.0.1", "dbName": "数据库名称,sqlite为文件路径比如a/x.db", @@ -62,7 +63,7 @@ var ConfigNote = Map{ "modeRouterStrict": "路由严格模式false,为大小写忽略必须匹配,true必须大小写匹配", //路由严格模式/a/b/c "connectLogShow": "如果需要web访问链接、访问ip、访问时间打印,0为关闭其他数字开启此功能", "sessionName": "设置session的cookie名默认HOTIME", - "port": "web服务开启Http端口,0为不启用http服务", + "port": "web服务开启Http端口,0为不启用http服务,默认80", "tlsPort": "web服务https端口,0为不启用https服务", "tlsKey": "https密钥", "tlsCert": "https证书",