重构日志与可观测性体系
新增单行文本编码器与结构化 GORM 日志,统一错误记录与请求日志策略,收紧日志文件权限并修复按天切分与压缩,支付回调参数脱敏,生产强制阿里云短信,RequestID 校验防注入,日志文案中文化。
This commit is contained in:
@@ -1,6 +1,7 @@
|
||||
package logging
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"strings"
|
||||
"time"
|
||||
@@ -18,47 +19,41 @@ func New(cfg config.LogConfig) (*zap.Logger, error) {
|
||||
}
|
||||
|
||||
level := zap.NewAtomicLevelAt(parseLevel(cfg.Level))
|
||||
encoderConfig := zap.NewProductionEncoderConfig()
|
||||
encoderConfig.TimeKey = "time"
|
||||
encoderConfig.LevelKey = "level"
|
||||
encoderConfig.MessageKey = "message"
|
||||
encoderConfig.CallerKey = "caller"
|
||||
encoderConfig.EncodeTime = func(t time.Time, enc zapcore.PrimitiveArrayEncoder) {
|
||||
enc.AppendString(t.In(location).Format("2006-01-02 15:04:05.000 -0700"))
|
||||
}
|
||||
encoderConfig.EncodeLevel = zapcore.CapitalLevelEncoder
|
||||
encoderConfig.EncodeDuration = zapcore.StringDurationEncoder
|
||||
encoderConfig.EncodeCaller = zapcore.ShortCallerEncoder
|
||||
|
||||
cores := make([]zapcore.Core, 0, 2)
|
||||
if cfg.EnableConsole {
|
||||
cores = append(cores, zapcore.NewCore(
|
||||
zapcore.NewConsoleEncoder(encoderConfig),
|
||||
newTextEncoder(location),
|
||||
zapcore.Lock(os.Stdout),
|
||||
level,
|
||||
))
|
||||
}
|
||||
if cfg.EnableFile {
|
||||
writer := newDailyWriter(cfg.Dir, "app", location, cfg.RetainDays)
|
||||
if err := writer.Open(); err != nil {
|
||||
return nil, fmt.Errorf("初始化日志文件失败: %w", err)
|
||||
}
|
||||
cores = append(cores, zapcore.NewCore(
|
||||
zapcore.NewJSONEncoder(encoderConfig),
|
||||
newTextEncoder(location),
|
||||
writer,
|
||||
level,
|
||||
))
|
||||
}
|
||||
if len(cores) == 0 {
|
||||
cores = append(cores, zapcore.NewCore(
|
||||
zapcore.NewConsoleEncoder(encoderConfig),
|
||||
newTextEncoder(location),
|
||||
zapcore.Lock(os.Stdout),
|
||||
level,
|
||||
))
|
||||
}
|
||||
|
||||
return zap.New(
|
||||
logger := zap.New(
|
||||
zapcore.NewTee(cores...),
|
||||
zap.AddCaller(),
|
||||
zap.AddStacktrace(zapcore.PanicLevel),
|
||||
), nil
|
||||
zap.ErrorOutput(zapcore.Lock(os.Stderr)),
|
||||
)
|
||||
zap.ReplaceGlobals(logger)
|
||||
return logger, nil
|
||||
}
|
||||
|
||||
func parseLevel(value string) zapcore.Level {
|
||||
|
||||
Reference in New Issue
Block a user