HTTP 用 Gin,配置用 Viper,日志用 zap,数据用 sqlx;保留原有接口与会商行为。 顺带补上就绪探活、请求号、滚动日志、systemd 与 Dockerfile。 Co-authored-by: Cursor <cursoragent@cursor.com>
100 lines
2.7 KiB
Go
100 lines
2.7 KiB
Go
// Package logging 提供进程级日志。
|
|
//
|
|
// 为什么用 zap:Gin 服务里最常见的结构化日志,字段稳定,方便按 jobId / reqId 检索。
|
|
// 约定:业务代码走 SugaredLogger 的 *w 方法(Infow/Warnw/Errorw),键名用本文件常量,不要自造别名。
|
|
// 边界:不写 token、密码、完整对话。失败详情在调用方截断后再传入。
|
|
package logging
|
|
|
|
import (
|
|
"os"
|
|
"strings"
|
|
|
|
"go.uber.org/zap"
|
|
"go.uber.org/zap/zapcore"
|
|
"gopkg.in/natefinch/lumberjack.v2"
|
|
)
|
|
|
|
// Options 日志初始化选项(对齐设计要求 §11)。
|
|
type Options struct {
|
|
Level string // debug|info|warn|error
|
|
File string // 非空则同时写滚动文件
|
|
MaxMB int
|
|
MaxAge int // 天
|
|
MaxBak int
|
|
}
|
|
|
|
// L 全局日志。Setup 之前是空实现,避免测试或提前打日志时空指针。
|
|
var L = zap.NewNop().Sugar()
|
|
|
|
// Setup 配置全局 zap:默认 stdout;LOG_FILE 非空时再加滚动文件。返回关闭函数(刷盘)。
|
|
//
|
|
// 用控制台编码器而不是 JSON:现有采集按 `jobId=` 这种键值对 grep,换 JSON 会让运维脚本对不上。
|
|
func Setup(opt Options) (closeFn func()) {
|
|
level := parseLevel(opt.Level)
|
|
encCfg := zap.NewDevelopmentEncoderConfig()
|
|
encCfg.EncodeTime = zapcore.ISO8601TimeEncoder
|
|
encCfg.EncodeLevel = zapcore.CapitalLevelEncoder
|
|
encCfg.EncodeCaller = zapcore.ShortCallerEncoder
|
|
encoder := zapcore.NewConsoleEncoder(encCfg)
|
|
|
|
writers := []zapcore.WriteSyncer{zapcore.AddSync(os.Stdout)}
|
|
closeFn = func() { _ = L.Sync() }
|
|
|
|
if path := strings.TrimSpace(opt.File); path != "" {
|
|
if opt.MaxMB <= 0 {
|
|
opt.MaxMB = 100
|
|
}
|
|
if opt.MaxAge <= 0 {
|
|
opt.MaxAge = 14
|
|
}
|
|
if opt.MaxBak <= 0 {
|
|
opt.MaxBak = 14
|
|
}
|
|
lj := &lumberjack.Logger{
|
|
Filename: path,
|
|
MaxSize: opt.MaxMB,
|
|
MaxAge: opt.MaxAge,
|
|
MaxBackups: opt.MaxBak,
|
|
LocalTime: true,
|
|
Compress: false,
|
|
}
|
|
writers = append(writers, zapcore.AddSync(lj))
|
|
prev := closeFn
|
|
closeFn = func() {
|
|
prev()
|
|
_ = lj.Close()
|
|
}
|
|
}
|
|
|
|
core := zapcore.NewCore(encoder, zapcore.NewMultiWriteSyncer(writers...), level)
|
|
logger := zap.New(core, zap.AddCaller())
|
|
zap.ReplaceGlobals(logger)
|
|
L = logger.Sugar()
|
|
return closeFn
|
|
}
|
|
|
|
func parseLevel(s string) zapcore.Level {
|
|
switch strings.ToLower(strings.TrimSpace(s)) {
|
|
case "debug":
|
|
return zapcore.DebugLevel
|
|
case "warn", "warning":
|
|
return zapcore.WarnLevel
|
|
case "error":
|
|
return zapcore.ErrorLevel
|
|
default:
|
|
return zapcore.InfoLevel
|
|
}
|
|
}
|
|
|
|
// 常用键名,方便 grep / 采集。调用方不要改成 job_id 这类别名。
|
|
const (
|
|
KeyJobID = "jobId"
|
|
KeyRequestID = "requestId"
|
|
KeyTaskID = "taskId"
|
|
KeyAccountID = "accountId"
|
|
KeyStatus = "status"
|
|
KeyPhase = "phase"
|
|
KeyModel = "model"
|
|
KeyReqID = "reqId"
|
|
)
|