u
This commit is contained in:
1 parent
2d036f4d95
commit
f373cf956d
22 files changed
+568
-280
No files matched your search
@@ -1,6 +1,8 @@
|
||||
package logx
|
||||
|
||||
import (
|
||||
"base-framework/pkg/routinex"
|
||||
"base-framework/pkg/utils/strutil"
|
||||
"base-framework/pkg/utils/uid"
|
||||
"fmt"
|
||||
"os"
|
||||
@@ -15,10 +17,9 @@ import (
|
||||
"go.uber.org/zap/zapcore"
|
||||
)
|
||||
|
||||
// ----------------- 全局变量 -----------------
|
||||
var (
|
||||
Logger *zap.Logger
|
||||
|
||||
Logger *zap.Logger
|
||||
TrackID = "trackId"
|
||||
once sync.Once
|
||||
currentDate string
|
||||
mu sync.Mutex
|
||||
@@ -32,10 +33,8 @@ var (
|
||||
errorCore zapcore.Core
|
||||
)
|
||||
|
||||
const LogID = "log_id"
|
||||
const logTmFmtWithMS = "2006-01-02 15:04:05.000"
|
||||
|
||||
// 彩色日志级别
|
||||
var levelColor = map[zapcore.Level]string{
|
||||
zapcore.DebugLevel: "\033[36mDEBUG\033[0m",
|
||||
zapcore.InfoLevel: "\033[32mINFO\033[0m",
|
||||
@@ -47,7 +46,7 @@ var levelColor = map[zapcore.Level]string{
|
||||
}
|
||||
|
||||
// ----------------- trackCore -----------------
|
||||
// trackCore 包装 zapcore.Core,实现自动生成 track_id
|
||||
// 在写入日志时自动从 routinex 获取 log_id 并加入字段
|
||||
type trackCore struct {
|
||||
zapcore.Core
|
||||
}
|
||||
@@ -64,20 +63,27 @@ func (c *trackCore) Check(entry zapcore.Entry, ce *zapcore.CheckedEntry) *zapcor
|
||||
}
|
||||
|
||||
func (c *trackCore) Write(entry zapcore.Entry, fields []zapcore.Field) error {
|
||||
hasTrackID := false
|
||||
for _, f := range fields {
|
||||
if f.Key == LogID {
|
||||
hasTrackID = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if !hasTrackID {
|
||||
fields = append(fields, Uint64(LogID, uid.NextID()))
|
||||
val := routinex.Get(TrackID)
|
||||
if val == nil {
|
||||
val = uid.NextID()
|
||||
routinex.Set(TrackID, val) // 保证同一请求复用同一 trackID
|
||||
}
|
||||
|
||||
fields = append(fields, zap.String(TrackID, strutil.ToString(val)))
|
||||
return c.Core.Write(entry, fields)
|
||||
}
|
||||
|
||||
// ----------------- 默认日志配置 -----------------
|
||||
// InitLogger ----------------- 初始化日志 -----------------
|
||||
func InitLogger() {
|
||||
once.Do(func() {
|
||||
if config.Log == nil {
|
||||
config.Log = defaultLogConfig()
|
||||
}
|
||||
createDirIfNotExist(config.Log.Dir)
|
||||
switchDate(time.Now().Format("2006-01-02"))
|
||||
})
|
||||
}
|
||||
|
||||
func defaultLogConfig() *types.Log {
|
||||
return &types.Log{
|
||||
Dir: "logs",
|
||||
@@ -91,21 +97,10 @@ func defaultLogConfig() *types.Log {
|
||||
}
|
||||
}
|
||||
|
||||
// ----------------- 初始化 -----------------
|
||||
func InitLogger() {
|
||||
once.Do(func() {
|
||||
if config.Log == nil {
|
||||
config.Log = defaultLogConfig()
|
||||
}
|
||||
createDirIfNotExist(config.Log.Dir)
|
||||
switchDate(time.Now().Format("2006-01-02"))
|
||||
})
|
||||
}
|
||||
|
||||
// ----------------- 初始化核心 -----------------
|
||||
func switchDate(today string) {
|
||||
currentDate = today
|
||||
|
||||
// 关闭旧文件
|
||||
if infoFile != nil {
|
||||
_ = infoFile.Close()
|
||||
}
|
||||
@@ -116,7 +111,6 @@ func switchDate(today string) {
|
||||
_ = errorFile.Close()
|
||||
}
|
||||
|
||||
// 文件路径
|
||||
infoPath, warnPath, errorPath := config.Log.Dir, config.Log.Dir, config.Log.Dir
|
||||
if config.Log.LevelDirs {
|
||||
infoPath = filepath.Join(config.Log.Dir, "info")
|
||||
@@ -129,12 +123,10 @@ func switchDate(today string) {
|
||||
createDirIfNotExist(config.Log.Dir)
|
||||
}
|
||||
|
||||
// 打开文件
|
||||
infoFile = getOrCreateFile(filepath.Join(infoPath, fmt.Sprintf("info-%s.log", today)))
|
||||
warnFile = getOrCreateFile(filepath.Join(warnPath, fmt.Sprintf("warn-%s.log", today)))
|
||||
errorFile = getOrCreateFile(filepath.Join(errorPath, fmt.Sprintf("error-%s.log", today)))
|
||||
|
||||
// 文件编码器
|
||||
var fileEncoder zapcore.Encoder
|
||||
if config.Log.Format == "console" {
|
||||
fileEncoder = newConsoleEncoder(false)
|
||||
@@ -142,32 +134,29 @@ func switchDate(today string) {
|
||||
fileEncoder = newJSONEncoder()
|
||||
}
|
||||
|
||||
// 文件核心
|
||||
infoCore = zapcore.NewCore(fileEncoder, zapcore.AddSync(infoFile), zap.LevelEnablerFunc(func(lvl zapcore.Level) bool {
|
||||
infoCore = &trackCore{zapcore.NewCore(fileEncoder, zapcore.AddSync(infoFile), zap.LevelEnablerFunc(func(lvl zapcore.Level) bool {
|
||||
return lvl <= zapcore.InfoLevel
|
||||
}))
|
||||
warnCore = zapcore.NewCore(fileEncoder, zapcore.AddSync(warnFile), zap.LevelEnablerFunc(func(lvl zapcore.Level) bool {
|
||||
}))}
|
||||
|
||||
warnCore = &trackCore{zapcore.NewCore(fileEncoder, zapcore.AddSync(warnFile), zap.LevelEnablerFunc(func(lvl zapcore.Level) bool {
|
||||
return lvl == zapcore.WarnLevel
|
||||
}))
|
||||
errorCore = zapcore.NewCore(fileEncoder, zapcore.AddSync(errorFile), zap.LevelEnablerFunc(func(lvl zapcore.Level) bool {
|
||||
}))}
|
||||
|
||||
errorCore = &trackCore{zapcore.NewCore(fileEncoder, zapcore.AddSync(errorFile), zap.LevelEnablerFunc(func(lvl zapcore.Level) bool {
|
||||
return lvl >= zapcore.ErrorLevel
|
||||
}))
|
||||
}))}
|
||||
|
||||
cores := []zapcore.Core{
|
||||
&trackCore{infoCore},
|
||||
&trackCore{warnCore},
|
||||
&trackCore{errorCore},
|
||||
}
|
||||
cores := []zapcore.Core{infoCore, warnCore, errorCore}
|
||||
|
||||
// 开启 console 输出
|
||||
if config.Log.Console {
|
||||
consoleCore := zapcore.NewCore(newConsoleEncoder(true), zapcore.AddSync(os.Stdout), zap.LevelEnablerFunc(func(lvl zapcore.Level) bool {
|
||||
consoleCore := &trackCore{zapcore.NewCore(newConsoleEncoder(true), zapcore.AddSync(os.Stdout), zap.LevelEnablerFunc(func(lvl zapcore.Level) bool {
|
||||
return lvl >= zapcore.DebugLevel
|
||||
}))
|
||||
cores = append(cores, &trackCore{consoleCore})
|
||||
}))}
|
||||
cores = append(cores, consoleCore)
|
||||
}
|
||||
|
||||
Logger = zap.New(zapcore.NewTee(cores...))
|
||||
|
||||
if config.Log.Caller {
|
||||
Logger = Logger.WithOptions(zap.AddCaller())
|
||||
} else {
|
||||
@@ -182,7 +171,6 @@ func switchDate(today string) {
|
||||
}))
|
||||
}
|
||||
|
||||
// ----------------- 编码器 -----------------
|
||||
func newConsoleEncoder(enableColor bool) zapcore.Encoder {
|
||||
cfg := zapcore.EncoderConfig{
|
||||
TimeKey: "ts",
|
||||
@@ -206,7 +194,7 @@ func newConsoleEncoder(enableColor bool) zapcore.Encoder {
|
||||
},
|
||||
EncodeCaller: func(caller zapcore.EntryCaller, enc zapcore.PrimitiveArrayEncoder) {
|
||||
pid := os.Getpid()
|
||||
enc.AppendString(fmt.Sprintf("[%d] %s", pid, caller.TrimmedPath()))
|
||||
enc.AppendString(fmt.Sprintf("[%d] [%d] %s", pid, routinex.CurGID(), caller.TrimmedPath()))
|
||||
},
|
||||
}
|
||||
return zapcore.NewConsoleEncoder(cfg)
|
||||
@@ -223,7 +211,6 @@ func newJSONEncoder() zapcore.Encoder {
|
||||
return zapcore.NewJSONEncoder(cfg)
|
||||
}
|
||||
|
||||
// ----------------- 工具函数 -----------------
|
||||
func checkDateSwitch() {
|
||||
today := time.Now().Format("2006-01-02")
|
||||
if today != currentDate {
|
||||
|
||||
Reference in new issue
Block a user