refactor(logging): 迁移日志记录到 Zerolog 并优化错误处理
- 将日志记录库从 Logrus 替换为 Zerolog,提升性能和灵活性 - 更新各个模块的日志记录方式,确保一致性 - 优化错误处理逻辑,确保在发生错误时能够正确记录并传递错误信息 - 移除不再使用的错误处理字段,简化代码结构 - 更新相关文档以反映新的日志记录和错误处理机制
This commit is contained in:
+61
-80
@@ -2,7 +2,6 @@ package hotime
|
||||
|
||||
import (
|
||||
"database/sql"
|
||||
"fmt"
|
||||
"io/ioutil"
|
||||
"net/http"
|
||||
"net/url"
|
||||
@@ -16,21 +15,19 @@ import (
|
||||
"code.hoteas.com/golang/hotime/code"
|
||||
. "code.hoteas.com/golang/hotime/common"
|
||||
. "code.hoteas.com/golang/hotime/db"
|
||||
. "code.hoteas.com/golang/hotime/log"
|
||||
"github.com/sirupsen/logrus"
|
||||
"code.hoteas.com/golang/hotime/log"
|
||||
)
|
||||
|
||||
type Application struct {
|
||||
MakeCodeRouter map[string]*code.MakeCode
|
||||
MethodRouter
|
||||
Router
|
||||
Error
|
||||
Log *logrus.Logger
|
||||
WebConnectLog *logrus.Logger
|
||||
Log *log.Logger
|
||||
WebConnectLog *log.Logger
|
||||
Port string //端口号
|
||||
TLSPort string //ssl访问端口号
|
||||
connectListener []func(that *Context) bool //所有的访问监听,true按原计划继续使用,false表示有监听器处理
|
||||
connectDbFunc func(err ...*Error) (master, slave *sql.DB)
|
||||
connectDbFunc func() (master, slave *sql.DB)
|
||||
configPath string
|
||||
Config Map
|
||||
Db HoTimeDB
|
||||
@@ -129,7 +126,7 @@ func (that *Application) Run(router Router) {
|
||||
defer func() {
|
||||
if err := recover(); err != nil {
|
||||
//that.SetError(errors.New(fmt.Sprint(err)), LOG_FMT)
|
||||
that.Log.Warn(err)
|
||||
that.Log.Warnf("%v", err)
|
||||
|
||||
that.Run(router)
|
||||
}
|
||||
@@ -149,7 +146,7 @@ func (that *Application) Run(router Router) {
|
||||
//启动服务
|
||||
that.Server.Addr = ":" + that.Port
|
||||
err := that.Server.ListenAndServe()
|
||||
that.Log.Error(err)
|
||||
that.Log.Error().Err(err).Msg("HTTP 服务退出")
|
||||
ch <- 1
|
||||
|
||||
}()
|
||||
@@ -163,33 +160,33 @@ func (that *Application) Run(router Router) {
|
||||
//启动服务
|
||||
that.Server.Addr = ":" + that.TLSPort
|
||||
err := that.Server.ListenAndServeTLS(that.Config.GetString("tlsCert"), that.Config.GetString("tlsKey"))
|
||||
that.Log.Error(err)
|
||||
that.Log.Error().Err(err).Msg("HTTPS 服务退出")
|
||||
ch <- 2
|
||||
|
||||
}()
|
||||
}
|
||||
if ObjToCeilInt(that.Port) == 0 && ObjToCeilInt(that.TLSPort) == 0 {
|
||||
that.Log.Error("没有端口启用")
|
||||
that.Log.Errorf("没有端口启用")
|
||||
return
|
||||
|
||||
}
|
||||
|
||||
value := <-ch
|
||||
|
||||
that.Log.Error("启动服务失败 : " + ObjToStr(value))
|
||||
that.Log.Errorf("启动服务失败 : %s", ObjToStr(value))
|
||||
}
|
||||
|
||||
// SetConnectDB 启动实例
|
||||
func (that *Application) SetConnectDB(connect func(err ...*Error) (master, slave *sql.DB)) {
|
||||
func (that *Application) SetConnectDB(connect func() (master, slave *sql.DB)) {
|
||||
|
||||
that.connectDbFunc = connect
|
||||
|
||||
that.Db.SetConnect(that.connectDbFunc, &that.Error)
|
||||
that.Db.SetConnect(that.connectDbFunc)
|
||||
|
||||
}
|
||||
|
||||
// SetDefault 默认配置缓存和session实现
|
||||
func (that *Application) SetDefault(connect func(err ...*Error) (*sql.DB, *sql.DB)) {
|
||||
func (that *Application) SetDefault(connect func() (*sql.DB, *sql.DB)) {
|
||||
that.SetConfig()
|
||||
|
||||
if connect != nil {
|
||||
@@ -202,19 +199,15 @@ func (that *Application) SetDefault(connect func(err ...*Error) (*sql.DB, *sql.D
|
||||
// SetCache 设置配置文件路径全路径或者相对路径
|
||||
func (that *Application) SetCache() {
|
||||
cacheIns := HoTimeCache{}
|
||||
cacheIns.Init(that.Config.GetMap("cache"), HoTimeDBInterface(&that.Db), &that.Error)
|
||||
cacheIns.Init(that.Config.GetMap("cache"), HoTimeDBInterface(&that.Db), that.Log)
|
||||
that.HoTimeCache = &cacheIns
|
||||
//mode生产模式开启的时候才开启数据库缓存,防止调试出问题
|
||||
if that.Config.GetInt("mode") == 0 {
|
||||
that.Db.HoTimeCache = &cacheIns
|
||||
}
|
||||
that.Db.HoTimeCache = &cacheIns
|
||||
}
|
||||
|
||||
// SetConfig 设置配置文件路径全路径或者相对路径
|
||||
func (that *Application) SetConfig(configPath ...string) {
|
||||
|
||||
that.Log = GetLog("", true)
|
||||
that.Error = Error{Logger: that.Log}
|
||||
that.Log = log.NewLogger(1, "", 100)
|
||||
if len(configPath) != 0 {
|
||||
that.configPath = configPath[0]
|
||||
}
|
||||
@@ -225,53 +218,45 @@ func (that *Application) SetConfig(configPath ...string) {
|
||||
//加载配置文件
|
||||
btes, err := ioutil.ReadFile(that.configPath)
|
||||
that.Config = DeepCopyMap(Config).(Map)
|
||||
configErr := false
|
||||
if err == nil {
|
||||
|
||||
cmap := Map{}
|
||||
//文件是否损坏
|
||||
cmap.JsonToMap(string(btes), &that.Error)
|
||||
cmap.JsonToMap(string(btes))
|
||||
|
||||
for k, v := range cmap {
|
||||
that.Config[k] = v //程序配置
|
||||
Config[k] = v //系统配置
|
||||
that.Config[k] = v
|
||||
Config[k] = v
|
||||
}
|
||||
} else {
|
||||
that.Log.Error("配置文件不存在,或者配置出错,使用缺省默认配置")
|
||||
|
||||
that.Log.Errorf("配置文件不存在,或者配置出错,使用缺省默认配置")
|
||||
}
|
||||
|
||||
if that.Error.GetError() != nil {
|
||||
fmt.Println(that.Error.GetError().Error())
|
||||
}
|
||||
|
||||
//文件如果损坏则不写入配置防止配置文件数据丢失
|
||||
if that.Error.GetError() == nil {
|
||||
//var configByte bytes.Buffer
|
||||
|
||||
//判断配置文件是否序列有变化,有则修改配置,无则不变
|
||||
//fmt.Println(len(btes))
|
||||
if !configErr {
|
||||
configStr := that.Config.ToJsonString()
|
||||
if len(btes) != 0 && configStr == string(btes) {
|
||||
return
|
||||
// 配置无变化,跳过写入
|
||||
} else {
|
||||
configNoteStr := ConfigNote.ToJsonString()
|
||||
_ = os.MkdirAll(filepath.Dir(that.configPath), os.ModeDir)
|
||||
err = ioutil.WriteFile(that.configPath, []byte(configStr), os.ModePerm)
|
||||
if err != nil {
|
||||
that.Log.Error().Err(err).Msg("写入配置文件失败")
|
||||
configErr = true
|
||||
}
|
||||
_ = ioutil.WriteFile(filepath.Dir(that.configPath)+"/configNote.json", []byte(configNoteStr), os.ModePerm)
|
||||
}
|
||||
//写入配置说明
|
||||
//var configNoteByte bytes.Buffer
|
||||
configNoteStr := ConfigNote.ToJsonString()
|
||||
//_ = json.Indent(&configNoteByte, []byte(ConfigNote.ToJsonString()), "", "\t")
|
||||
|
||||
_ = os.MkdirAll(filepath.Dir(that.configPath), os.ModeDir)
|
||||
err = ioutil.WriteFile(that.configPath, []byte(configStr), os.ModePerm)
|
||||
if err != nil {
|
||||
that.Error.SetError(err)
|
||||
}
|
||||
_ = ioutil.WriteFile(filepath.Dir(that.configPath)+"/configNote.json", []byte(configNoteStr), os.ModePerm)
|
||||
|
||||
}
|
||||
|
||||
that.Log = GetLog(that.Config.GetString("logFile"), true)
|
||||
that.Error = Error{Logger: that.Log}
|
||||
logLevel := that.Config.GetCeilInt("logLevel")
|
||||
logFile := that.Config.GetString("logFile")
|
||||
logHistory := that.Config.GetCeilInt("logHistory")
|
||||
if logHistory == 0 {
|
||||
logHistory = 100
|
||||
}
|
||||
that.Log = log.NewLogger(logLevel, logFile, logHistory)
|
||||
that.Db.Log = that.Log
|
||||
if that.Config.Get("webConnectLogShow") == nil || that.Config.GetBool("webConnectLogShow") {
|
||||
that.WebConnectLog = GetLog(that.Config.GetString("webConnectLogFile"), false)
|
||||
that.WebConnectLog = log.NewLogger(1, that.Config.GetString("webConnectLogFile"), 0)
|
||||
}
|
||||
|
||||
}
|
||||
@@ -377,9 +362,12 @@ func (that *Application) handler(w http.ResponseWriter, req *http.Request) {
|
||||
ipStr = Substr(context.Req.RemoteAddr, 0, strings.Index(context.Req.RemoteAddr, ":"))
|
||||
}
|
||||
|
||||
that.WebConnectLog.Infoln(ipStr, context.Req.Method,
|
||||
"time cost:", ObjToFloat64(time.Now().UnixNano()-nowUnixTime.UnixNano())/1000000.00, "ms",
|
||||
"data length:", ObjToFloat64(context.DataSize)/1000.00, "KB", context.HandlerStr)
|
||||
that.WebConnectLog.Info().
|
||||
Str("ip", ipStr).
|
||||
Str("method", context.Req.Method).
|
||||
Float64("cost_ms", ObjToFloat64(time.Now().UnixNano()-nowUnixTime.UnixNano())/1000000.00).
|
||||
Float64("size_kb", ObjToFloat64(context.DataSize)/1000.00).
|
||||
Msg(context.HandlerStr)
|
||||
}
|
||||
}()
|
||||
|
||||
@@ -441,7 +429,7 @@ func (that *Application) handler(w http.ResponseWriter, req *http.Request) {
|
||||
|
||||
//设置header
|
||||
delete(header, "Content-Type")
|
||||
if that.Config.GetInt("mode") == 0 {
|
||||
if that.Config.GetCeilInt("logLevel") == 0 {
|
||||
header.Set("Cache-Control", "public")
|
||||
} else {
|
||||
header.Set("Cache-Control", "no-cache")
|
||||
@@ -580,7 +568,7 @@ func Init(config string) *Application {
|
||||
codeMake["name"] = codeMake.GetString("table")
|
||||
}
|
||||
|
||||
appIns.MakeCodeRouter[codeMake.GetString("name")] = &code.MakeCode{Error: appIns.Error}
|
||||
appIns.MakeCodeRouter[codeMake.GetString("name")] = &code.MakeCode{Log: appIns.Log}
|
||||
appIns.MakeCodeRouter[codeMake.GetString("name")].Db2JSON(&appIns.Db, codeMake)
|
||||
|
||||
//接入动态代码层
|
||||
@@ -644,45 +632,39 @@ func SetMysqlDB(appIns *Application, config Map) {
|
||||
appIns.Db.DBName = config.GetString("name")
|
||||
appIns.Db.Prefix = config.GetString("prefix")
|
||||
appIns.Db.Log = appIns.Log
|
||||
appIns.Db.Mode = appIns.Config.GetCeilInt("mode")
|
||||
appIns.SetConnectDB(func(err ...*Error) (master, slave *sql.DB) {
|
||||
//master数据库配置
|
||||
appIns.SetConnectDB(func() (master, slave *sql.DB) {
|
||||
query := config.GetString("user") + ":" + config.GetString("password") +
|
||||
"@tcp(" + config.GetString("host") + ":" + config.GetString("port") + ")/" + config.GetString("name") + "?charset=utf8"
|
||||
DB, e := sql.Open("mysql", query)
|
||||
if e != nil && len(err) != 0 {
|
||||
err[0].SetError(e)
|
||||
if e != nil {
|
||||
appIns.Log.Error().Err(e).Msg("MySQL 主库连接失败")
|
||||
}
|
||||
master = DB
|
||||
//slave数据库配置
|
||||
configSlave := config.GetMap("slave")
|
||||
if configSlave != nil {
|
||||
query := configSlave.GetString("user") + ":" + configSlave.GetString("password") +
|
||||
"@tcp(" + config.GetString("host") + ":" + configSlave.GetString("port") + ")/" + configSlave.GetString("name") + "?charset=utf8"
|
||||
DB1, e := sql.Open("mysql", query)
|
||||
if e != nil && len(err) != 0 {
|
||||
err[0].SetError(e)
|
||||
if e != nil {
|
||||
appIns.Log.Error().Err(e).Msg("MySQL 从库连接失败")
|
||||
}
|
||||
slave = DB1
|
||||
}
|
||||
|
||||
return master, slave
|
||||
//return DB
|
||||
})
|
||||
}
|
||||
func SetSqliteDB(appIns *Application, config Map) {
|
||||
|
||||
appIns.Db.Type = "sqlite"
|
||||
appIns.Db.Prefix = config.GetString("prefix")
|
||||
appIns.Db.Mode = appIns.Config.GetCeilInt("mode")
|
||||
appIns.Db.Log = appIns.Log
|
||||
appIns.SetConnectDB(func(err ...*Error) (master, slave *sql.DB) {
|
||||
appIns.SetConnectDB(func() (master, slave *sql.DB) {
|
||||
db, e := sql.Open("sqlite3", config.GetString("path"))
|
||||
if e != nil && len(err) != 0 {
|
||||
err[0].SetError(e)
|
||||
if e != nil {
|
||||
appIns.Log.Error().Err(e).Msg("SQLite 连接失败")
|
||||
}
|
||||
master = db
|
||||
|
||||
return master, slave
|
||||
})
|
||||
}
|
||||
@@ -692,13 +674,12 @@ func SetDmDB(appIns *Application, config Map) {
|
||||
appIns.Db.DBName = config.GetString("name")
|
||||
appIns.Db.Prefix = config.GetString("prefix")
|
||||
appIns.Db.Log = appIns.Log
|
||||
appIns.Db.Mode = appIns.Config.GetCeilInt("mode")
|
||||
appIns.SetConnectDB(func(err ...*Error) (master, slave *sql.DB) {
|
||||
appIns.SetConnectDB(func() (master, slave *sql.DB) {
|
||||
query := "dm://" + config.GetString("user") + ":" + config.GetString("password") +
|
||||
"@" + config.GetString("host") + ":" + config.GetString("port") + "?schema=" + config.GetString("name")
|
||||
DB, e := sql.Open("dm", query)
|
||||
if e != nil && len(err) != 0 {
|
||||
err[0].SetError(e)
|
||||
if e != nil {
|
||||
appIns.Log.Error().Err(e).Msg("达梦主库连接失败")
|
||||
}
|
||||
master = DB
|
||||
configSlave := config.GetMap("slave")
|
||||
@@ -706,8 +687,8 @@ func SetDmDB(appIns *Application, config Map) {
|
||||
querySlave := "dm://" + configSlave.GetString("user") + ":" + configSlave.GetString("password") +
|
||||
"@" + configSlave.GetString("host") + ":" + configSlave.GetString("port") + "?schema=" + configSlave.GetString("name")
|
||||
DB1, e := sql.Open("dm", querySlave)
|
||||
if e != nil && len(err) != 0 {
|
||||
err[0].SetError(e)
|
||||
if e != nil {
|
||||
appIns.Log.Error().Err(e).Msg("达梦从库连接失败")
|
||||
}
|
||||
slave = DB1
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user