新增单行文本编码器与结构化 GORM 日志,统一错误记录与请求日志策略,收紧日志文件权限并修复按天切分与压缩,支付回调参数脱敏,生产强制阿里云短信,RequestID 校验防注入,日志文案中文化。
71 lines
1.4 KiB
Go
71 lines
1.4 KiB
Go
package logging
|
|
|
|
import (
|
|
"fmt"
|
|
"os"
|
|
"strings"
|
|
"time"
|
|
|
|
"hfb_sys/backend/internal/config"
|
|
|
|
"go.uber.org/zap"
|
|
"go.uber.org/zap/zapcore"
|
|
)
|
|
|
|
func New(cfg config.LogConfig) (*zap.Logger, error) {
|
|
location, err := time.LoadLocation("Asia/Shanghai")
|
|
if err != nil {
|
|
location = time.FixedZone("Asia/Shanghai", 8*60*60)
|
|
}
|
|
|
|
level := zap.NewAtomicLevelAt(parseLevel(cfg.Level))
|
|
cores := make([]zapcore.Core, 0, 2)
|
|
if cfg.EnableConsole {
|
|
cores = append(cores, zapcore.NewCore(
|
|
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(
|
|
newTextEncoder(location),
|
|
writer,
|
|
level,
|
|
))
|
|
}
|
|
if len(cores) == 0 {
|
|
cores = append(cores, zapcore.NewCore(
|
|
newTextEncoder(location),
|
|
zapcore.Lock(os.Stdout),
|
|
level,
|
|
))
|
|
}
|
|
|
|
logger := zap.New(
|
|
zapcore.NewTee(cores...),
|
|
zap.AddCaller(),
|
|
zap.AddStacktrace(zapcore.PanicLevel),
|
|
zap.ErrorOutput(zapcore.Lock(os.Stderr)),
|
|
)
|
|
zap.ReplaceGlobals(logger)
|
|
return logger, nil
|
|
}
|
|
|
|
func parseLevel(value string) zapcore.Level {
|
|
switch strings.ToLower(strings.TrimSpace(value)) {
|
|
case "debug":
|
|
return zapcore.DebugLevel
|
|
case "warn", "warning":
|
|
return zapcore.WarnLevel
|
|
case "error":
|
|
return zapcore.ErrorLevel
|
|
default:
|
|
return zapcore.InfoLevel
|
|
}
|
|
}
|