This commit is contained in:
oneao committed 2025-11-26 22:36:39 +08:00
1 parent b9f728812d
commit d9b2522552
12 files changed
+104 -19

No files matched your search

+120
View File
@@ -0,0 +1,120 @@
package logx
import (
"fmt"
"os"
"sync"
"time"
"github.com/cloudwego/hertz/pkg/common/hlog"
"go.uber.org/zap"
"go.uber.org/zap/zapcore"
"gopkg.in/natefinch/lumberjack.v2"
)
var (
// 暴露底层 zap logger 供 logreq 使用
zapLogger *zap.Logger
)
func InitLog() {
dynamicLevel := zap.NewAtomicLevel()
dynamicLevel.SetLevel(zap.DebugLevel)
logger := NewLogger(
WithCores([]CoreConfig{
{
Enc: zapcore.NewJSONEncoder(humanEncoderConfig()),
Ws: zapcore.AddSync(os.Stdout),
Lvl: dynamicLevel,
},
{
Enc: zapcore.NewJSONEncoder(humanEncoderConfig()),
Ws: getWriteSyncer("./logs/debug"),
Lvl: zap.LevelEnablerFunc(func(lev zapcore.Level) bool {
return lev == zap.DebugLevel
}),
},
{
Enc: zapcore.NewJSONEncoder(humanEncoderConfig()),
Ws: getWriteSyncer("./logs/info"),
Lvl: zap.LevelEnablerFunc(func(lev zapcore.Level) bool {
return lev == zap.InfoLevel
}),
},
{
Enc: zapcore.NewJSONEncoder(humanEncoderConfig()),
Ws: getWriteSyncer("./logs/warn"),
Lvl: zap.LevelEnablerFunc(func(lev zapcore.Level) bool {
return lev == zap.WarnLevel
}),
},
{
Enc: zapcore.NewJSONEncoder(humanEncoderConfig()),
Ws: getWriteSyncer("./logs/error"),
Lvl: zap.LevelEnablerFunc(func(lev zapcore.Level) bool {
return lev >= zap.ErrorLevel
}),
},
}...),
)
hlog.SetLogger(logger)
zapLogger = logger.Logger()
}
// humanEncoderConfig copy from zap
func humanEncoderConfig() zapcore.EncoderConfig {
return zapcore.EncoderConfig{
MessageKey: "Message",
LevelKey: "Level",
NameKey: "Name",
TimeKey: "Ts",
CallerKey: "Caller",
FunctionKey: "Func",
StacktraceKey: "Stacktrace",
LineEnding: "\n",
EncodeTime: zapcore.ISO8601TimeEncoder,
EncodeLevel: zapcore.LowercaseLevelEncoder,
EncodeDuration: zapcore.SecondsDurationEncoder,
EncodeCaller: zapcore.ShortCallerEncoder,
}
}
var (
mu sync.Mutex
currentDay = make(map[string]string)
currentSync = make(map[string]zapcore.WriteSyncer)
)
func getWriteSyncer(basePath string) zapcore.WriteSyncer {
mu.Lock()
defer mu.Unlock()
today := time.Now().Format("2006-01-02")
if day, ok := currentDay[basePath]; !ok || day != today {
currentDay[basePath] = today
file := fmt.Sprintf("%s/%s.log", basePath, today)
currentSync[basePath] = zapcore.AddSync(&lumberjack.Logger{
Filename: file,
MaxSize: 10,
MaxBackups: 50000,
MaxAge: 5,
Compress: true,
LocalTime: true,
})
}
return currentSync[basePath]
}
func Sync() error {
if zapLogger != nil {
return zapLogger.Sync()
}
return nil
}
func GetZapLogger() *zap.Logger {
return zapLogger
}