use logrus to project default log tools

This commit is contained in:
hoteas
2021-05-25 05:08:17 +08:00
parent 9bc930750d
commit df07afb744
15 changed files with 491 additions and 457 deletions
+115 -106
View File
@@ -4,6 +4,7 @@ import (
. "./cache"
. "./common"
. "./db"
. "./log"
"bytes"
"database/sql"
"encoding/json"
@@ -21,7 +22,8 @@ type Application struct {
MethodRouter
Router
ContextBase
Log logrus.Logger
Log *logrus.Logger
WebConnectLog *logrus.Logger
Port string //端口号
TLSPort string //ssl访问端口号
connectListener []func(this *Context) bool //所有的访问监听,true按原计划继续使用,false表示有监听器处理
@@ -29,44 +31,44 @@ type Application struct {
configPath string
Config Map
Db HoTimeDB
Server *http.Server
*http.Server
CacheIns
sessionLong CacheIns
sessionShort CacheIns
http.Handler
}
func (this *Application) ServeHTTP(w http.ResponseWriter, req *http.Request) {
this.handler(w, req)
func (that *Application) ServeHTTP(w http.ResponseWriter, req *http.Request) {
that.handler(w, req)
}
//启动实例
func (this *Application) Run(router Router) {
// Run 启动实例
func (that *Application) Run(router Router) {
//如果没有设置配置自动生成配置
if this.configPath == "" || len(this.Config) == 0 {
this.SetConfig()
if that.configPath == "" || len(that.Config) == 0 {
that.SetConfig()
}
//防止手动设置缓存误伤
if this.CacheIns == nil {
this.SetCache(CacheIns(&CacheMemory{}))
if that.CacheIns == nil {
that.SetCache(CacheIns(&CacheMemory{}))
}
//防止手动设置session误伤
//if this.sessionShort == nil && this.sessionLong == nil {
// if this.connectDbFunc == nil {
// this.SetSession(CacheIns(&CacheMemory{}), nil)
//if that.sessionShort == nil && that.sessionLong == nil {
// if that.connectDbFunc == nil {
// that.SetSession(CacheIns(&CacheMemory{}), nil)
// } else {
// this.SetSession(CacheIns(&CacheMemory{}), CacheIns(&CacheDb{Db: &this.Db, Time: this.Config.GetInt64("cacheLongTime")}))
// that.SetSession(CacheIns(&CacheMemory{}), CacheIns(&CacheDb{Db: &that.Db, Time: that.Config.GetInt64("cacheLongTime")}))
// }
//
//}
this.Router = router
that.Router = router
//重新设置MethodRouter//直达路由
this.MethodRouter = MethodRouter{}
that.MethodRouter = MethodRouter{}
modeRouterStrict := true
if this.Config.Get("modeRouterStrict").(bool) == false {
if that.Config.GetBool("modeRouterStrict") == false {
modeRouterStrict = false
}
if router != nil {
@@ -84,7 +86,7 @@ func (this *Application) Run(router Router) {
if !modeRouterStrict {
mk = strings.ToLower(mk)
}
this.MethodRouter["/"+pk+"/"+ck+"/"+mk] = mv
that.MethodRouter["/"+pk+"/"+ck+"/"+mk] = mv
}
}
}
@@ -92,137 +94,139 @@ func (this *Application) Run(router Router) {
}
}
//this.Port = port
this.Port = this.Config.GetString("port")
this.TLSPort = this.Config.GetString("tlsPort")
//that.Port = port
that.Port = that.Config.GetString("port")
that.TLSPort = that.Config.GetString("tlsPort")
if this.connectDbFunc != nil && (this.Db.DB == nil || this.Db.DB.Ping() != nil) {
this.Db.SetConnect(this.connectDbFunc)
if that.connectDbFunc != nil && (that.Db.DB == nil || that.Db.DB.Ping() != nil) {
that.Db.SetConnect(that.connectDbFunc)
}
if this.CacheIns == nil {
this.CacheIns = CacheIns(&CacheMemory{Map: Map{}, Time: this.Config.GetInt64("cacheShortTime")})
if that.CacheIns == nil {
that.CacheIns = CacheIns(&CacheMemory{Map: Map{}, Time: that.Config.GetInt64("cacheShortTime")})
}
//异常处理
defer func() {
if err := recover(); err != nil {
//this.SetError(errors.New(fmt.Sprint(err)), LOG_FMT)
LogFmt(err, 2, LOG_ERROR)
//that.SetError(errors.New(fmt.Sprint(err)), LOG_FMT)
that.Log.Warn(err)
this.Run(router)
that.Run(router)
}
}()
this.Server = &http.Server{}
that.Server = &http.Server{}
if !IsRun {
IsRun = true
}
ch := make(chan int)
if ObjToCeilInt(this.Port) != 0 {
if ObjToCeilInt(that.Port) != 0 {
go func() {
App[this.Port] = this
this.Server.Handler = this
App[that.Port] = that
that.Server.Handler = that
//启动服务
this.Server.Addr = ":" + this.Port
err := this.Server.ListenAndServe()
LogFmt(err, 2)
that.Server.Addr = ":" + that.Port
err := that.Server.ListenAndServe()
that.Log.Error(err)
ch <- 1
}()
}
if ObjToCeilInt(this.TLSPort) != 0 {
if ObjToCeilInt(that.TLSPort) != 0 {
go func() {
App[this.TLSPort] = this
this.Server.Handler = this
App[that.TLSPort] = that
that.Server.Handler = that
//启动服务
this.Server.Addr = ":" + this.TLSPort
err := this.Server.ListenAndServeTLS(this.Config.GetString("tlsCert"), this.Config.GetString("tlsKey"))
LogFmt(err, 2)
that.Server.Addr = ":" + that.TLSPort
err := that.Server.ListenAndServeTLS(that.Config.GetString("tlsCert"), that.Config.GetString("tlsKey"))
that.Log.Error(err)
ch <- 2
}()
}
if ObjToCeilInt(this.Port) == 0 && ObjToCeilInt(this.TLSPort) == 0 {
LogFmt("没有端口启用", 2, LOG_INFO)
if ObjToCeilInt(that.Port) == 0 && ObjToCeilInt(that.TLSPort) == 0 {
that.Log.Error("没有端口启用")
return
}
value := <-ch
LogFmt("启动服务失败 : "+ObjToStr(value), 2, LOG_ERROR)
that.Log.Error("启动服务失败 : " + ObjToStr(value))
}
//启动实例
func (this *Application) SetConnectDB(connect func(err ...*Error) (master, slave *sql.DB)) {
// SetConnectDB 启动实例
func (that *Application) SetConnectDB(connect func(err ...*Error) (master, slave *sql.DB)) {
this.connectDbFunc = connect
this.Db.SetConnect(this.connectDbFunc)
that.connectDbFunc = connect
that.Db.SetConnect(that.connectDbFunc)
}
//设置配置文件路径全路径或者相对路径
func (this *Application) SetSession(short CacheIns, Long CacheIns) {
this.sessionLong = Long
this.sessionShort = short
// SetSession 设置配置文件路径全路径或者相对路径
func (that *Application) SetSession(short CacheIns, Long CacheIns) {
that.sessionLong = Long
that.sessionShort = short
}
//默认配置缓存和session实现
func (this *Application) SetDefault(connect func(err ...*Error) (*sql.DB, *sql.DB)) {
this.SetConfig()
// SetDefault 默认配置缓存和session实现
func (that *Application) SetDefault(connect func(err ...*Error) (*sql.DB, *sql.DB)) {
that.SetConfig()
if connect != nil {
this.connectDbFunc = connect
this.Db.SetConnect(this.connectDbFunc)
that.connectDbFunc = connect
that.Db.SetConnect(that.connectDbFunc)
}
}
//设置配置文件路径全路径或者相对路径
func (this *Application) SetCache(cache CacheIns) {
// SetCache 设置配置文件路径全路径或者相对路径
func (that *Application) SetCache(cache CacheIns) {
this.CacheIns = cache
that.CacheIns = cache
}
//设置配置文件路径全路径或者相对路径
func (this *Application) SetConfig(configPath ...string) {
// SetConfig 设置配置文件路径全路径或者相对路径
func (that *Application) SetConfig(configPath ...string) {
that.Log = GetLog("", true)
if len(configPath) != 0 {
this.configPath = configPath[0]
that.configPath = configPath[0]
}
if this.configPath == "" {
this.configPath = "config/config.json"
if that.configPath == "" {
that.configPath = "config/config.json"
}
//加载配置文件
btes, err := ioutil.ReadFile(this.configPath)
this.Config = DeepCopyMap(Config).(Map)
btes, err := ioutil.ReadFile(that.configPath)
that.Config = DeepCopyMap(Config).(Map)
if err == nil {
cmap := Map{}
//文件是否损坏
cmap.JsonToMap(string(btes), &this.Error)
cmap.JsonToMap(string(btes), &that.Error)
for k, v := range cmap {
this.Config[k] = v //程序配置
that.Config[k] = v //程序配置
Config[k] = v //系统配置
}
} else {
LogFmt("配置文件不存在,或者配置出错,使用缺省默认配置", 2)
that.Log.Error("配置文件不存在,或者配置出错,使用缺省默认配置")
}
//文件如果损坏则不写入配置防止配置文件数据丢失
if this.Error.GetError() == nil {
if that.Error.GetError() == nil {
var configByte bytes.Buffer
err = json.Indent(&configByte, []byte(this.Config.ToJsonString()), "", "\t")
err = json.Indent(&configByte, []byte(that.Config.ToJsonString()), "", "\t")
//判断配置文件是否序列有变化有则修改配置,五则不变
//fmt.Println(len(btes))
if len(btes) != 0 && configByte.String() == string(btes) {
@@ -230,22 +234,26 @@ func (this *Application) SetConfig(configPath ...string) {
}
//写入配置说明
var configNoteByte bytes.Buffer
json.Indent(&configNoteByte, []byte(ConfigNote.ToJsonString()), "", "\t")
_ = json.Indent(&configNoteByte, []byte(ConfigNote.ToJsonString()), "", "\t")
os.MkdirAll(filepath.Dir(this.configPath), os.ModeDir)
err = ioutil.WriteFile(this.configPath, configByte.Bytes(), os.ModeAppend)
_ = os.MkdirAll(filepath.Dir(that.configPath), os.ModeDir)
err = ioutil.WriteFile(that.configPath, configByte.Bytes(), os.ModeAppend)
if err != nil {
this.Error.SetError(err)
that.Error.SetError(err)
}
ioutil.WriteFile(filepath.Dir(this.configPath)+"/confignote.json", configNoteByte.Bytes(), os.ModeAppend)
_ = ioutil.WriteFile(filepath.Dir(that.configPath)+"/configNote.json", configNoteByte.Bytes(), os.ModeAppend)
}
that.Log = GetLog(that.Config.GetString("logFile"), true)
if that.Config.GetBool("webConnectLogShow") {
that.WebConnectLog = GetLog(that.Config.GetString("webConnectLogFile"), false)
}
}
//连接判断,返回true继续传输至控制层,false则停止传输
func (this *Application) SetConnectListener(lis func(this *Context) bool) {
this.connectListener = append(this.connectListener, lis)
// SetConnectListener 连接判断,返回true继续传输至控制层,false则停止传输
func (that *Application) SetConnectListener(lis func(this *Context) bool) {
that.connectListener = append(that.connectListener, lis)
}
//网络错误
@@ -254,7 +262,7 @@ func (this *Application) SetConnectListener(lis func(this *Context) bool) {
//}
//序列化链接
func (this *Application) urlSer(url string) (string, []string) {
func (that *Application) urlSer(url string) (string, []string) {
q := strings.Index(url, "?")
if q == -1 {
q = len(url)
@@ -275,9 +283,9 @@ func (this *Application) urlSer(url string) (string, []string) {
//访问
func (this *Application) handler(w http.ResponseWriter, req *http.Request) {
func (that *Application) handler(w http.ResponseWriter, req *http.Request) {
_, s := this.urlSer(req.RequestURI)
_, s := that.urlSer(req.RequestURI)
//获取cookie
// 如果cookie存在直接将sessionId赋值为cookie.Value
// 如果cookie不存在就查找传入的参数中是否有token
@@ -285,7 +293,7 @@ func (this *Application) handler(w http.ResponseWriter, req *http.Request) {
// 如果token存在就判断token是否在Session中有保存
// 如果有取出token并复制给cookie
// 没有保存就生成随机的session
cookie, err := req.Cookie(this.Config.GetString("sessionName"))
cookie, err := req.Cookie(that.Config.GetString("sessionName"))
sessionId := Md5(strconv.Itoa(Rand(10)))
token := req.FormValue("token")
//isFirst:=false
@@ -296,7 +304,7 @@ func (this *Application) handler(w http.ResponseWriter, req *http.Request) {
//else{
// isFirst=true;
//}
http.SetCookie(w, &http.Cookie{Name: this.Config.GetString("sessionName"), Value: sessionId, Path: "/"})
http.SetCookie(w, &http.Cookie{Name: that.Config.GetString("sessionName"), Value: sessionId, Path: "/"})
} else {
sessionId = cookie.Value
}
@@ -307,31 +315,31 @@ func (this *Application) handler(w http.ResponseWriter, req *http.Request) {
}
//访问实例
context := Context{SessionIns: SessionIns{SessionId: sessionId,
LongCache: this.sessionLong,
ShortCache: this.sessionShort,
LongCache: that.sessionLong,
ShortCache: that.sessionShort,
},
CacheIns: this.CacheIns,
Resp: w, Req: req, Application: this, RouterString: s, Config: this.Config, Db: &this.Db, HandlerStr: unescapeUrl}
CacheIns: that.CacheIns,
Resp: w, Req: req, Application: that, RouterString: s, Config: that.Config, Db: &that.Db, HandlerStr: unescapeUrl}
//header默认设置
header := w.Header()
header.Set("Content-Type", "text/html; charset=utf-8")
//url去掉参数并序列化
context.HandlerStr, context.RouterString = this.urlSer(context.HandlerStr)
context.HandlerStr, context.RouterString = that.urlSer(context.HandlerStr)
//跨域设置
this.crossDomain(&context)
that.crossDomain(&context)
//是否展示日志
if this.Config.GetInt("connectLogShow") != 0 {
LogFmt(Substr(context.Req.RemoteAddr, 0, strings.Index(context.Req.RemoteAddr, ":"))+" "+context.HandlerStr, 0, LOG_INFO)
if that.WebConnectLog != nil {
that.WebConnectLog.Infoln(Substr(context.Req.RemoteAddr, 0, strings.Index(context.Req.RemoteAddr, ":")) + " " + context.HandlerStr)
}
//访问拦截true继续false暂停
connectListenerLen := len(this.connectListener)
connectListenerLen := len(that.connectListener)
if connectListenerLen != 0 {
for i := 0; i < connectListenerLen; i++ {
if !this.connectListener[i](&context) {
if !that.connectListener[i](&context) {
context.View()
return
@@ -342,9 +350,9 @@ func (this *Application) handler(w http.ResponseWriter, req *http.Request) {
//接口服务
//if len(s) == 3 {
// //如果满足规则则路由到对应控制器去
// if this.Router[s[0]] != nil && this.Router[s[0]][s[1]] != nil && this.Router[s[0]][s[1]][s[2]] != nil {
// if that.Router[s[0]] != nil && that.Router[s[0]][s[1]] != nil && that.Router[s[0]][s[1]][s[2]] != nil {
// //控制层
// this.Router[s[0]][s[1]][s[2]](&context)
// that.Router[s[0]][s[1]][s[2]](&context)
// //header.Set("Content-Type", "text/html; charset=utf-8")
// context.View()
// return
@@ -352,25 +360,25 @@ func (this *Application) handler(w http.ResponseWriter, req *http.Request) {
//
//}
//验证接口严格模式
modeRouterStrict := this.Config.Get("modeRouterStrict").(bool)
modeRouterStrict := that.Config.GetBool("modeRouterStrict")
tempHandlerStr := context.HandlerStr
if !modeRouterStrict {
tempHandlerStr = strings.ToLower(tempHandlerStr)
}
//执行接口
if this.MethodRouter[tempHandlerStr] != nil {
this.MethodRouter[tempHandlerStr](&context)
if that.MethodRouter[tempHandlerStr] != nil {
that.MethodRouter[tempHandlerStr](&context)
context.View()
return
}
//url赋值
path := this.Config.GetString("tpt") + tempHandlerStr
path := that.Config.GetString("tpt") + tempHandlerStr
//判断是否为默认
if path[len(path)-1] == '/' {
defFile := this.Config.GetSlice("defFile")
defFile := that.Config.GetSlice("defFile")
for i := 0; i < len(defFile); i++ {
temp := path + defFile.GetString(i)
@@ -394,7 +402,7 @@ func (this *Application) handler(w http.ResponseWriter, req *http.Request) {
//设置header
delete(header, "Content-Type")
if this.Config.GetInt("debug") != 1 {
if that.Config.GetInt("debug") != 1 {
header.Set("Cache-Control", "public")
}
@@ -407,7 +415,7 @@ func (this *Application) handler(w http.ResponseWriter, req *http.Request) {
}
func (this *Application) crossDomain(context *Context) {
func (that *Application) crossDomain(context *Context) {
//没有跨域设置
if context.Config.GetString("crossDomain") == "" {
return
@@ -421,7 +429,7 @@ func (this *Application) crossDomain(context *Context) {
header.Set("Access-Control-Allow-Headers", "X-Requested-With,Content-Type,Access-Token")
if context.Config.GetString("crossDomain") != "auto" {
header.Set("Access-Control-Allow-Origin", this.Config.GetString("crossDomain"))
header.Set("Access-Control-Allow-Origin", that.Config.GetString("crossDomain"))
return
}
@@ -450,6 +458,7 @@ func (this *Application) crossDomain(context *Context) {
}
}
//Init 初始化application
func Init(config string) Application {
appIns := Application{}
//手动模式,
@@ -459,7 +468,7 @@ func Init(config string) Application {
return appIns
}
//后期整改
// SetDB 智能数据库设置
func SetDB(appIns *Application) {
db := appIns.Config.GetMap("db")
dbSqlite := db.GetMap("sqlite")