Files
CamTalk/backend/internal/logger/logger.go
hhs d5d584c93b feat: 实现 Zap 日志封装
- 新增 internal/logger/logger.go
- 提供 Init(level, format) 初始化全局 SugaredLogger
- 支持 json/console 两种格式
- 提供 Sync() 刷新缓冲区
2026-06-13 15:17:26 +08:00

58 lines
1.1 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
package logger
import (
"os"
"go.uber.org/zap"
"go.uber.org/zap/zapcore"
)
// Log 是全局 SugaredLogger由 Init 初始化。
var Log *zap.SugaredLogger
// Init 初始化全局日志器。
// level: "debug", "info", "warn", "error"
// format: "json" 或 "console"
func Init(level, format string) {
var lvl zapcore.Level
switch level {
case "debug":
lvl = zapcore.DebugLevel
case "warn":
lvl = zapcore.WarnLevel
case "error":
lvl = zapcore.ErrorLevel
default:
lvl = zapcore.InfoLevel
}
encoderCfg := zap.NewProductionEncoderConfig()
encoderCfg.TimeKey = "ts"
encoderCfg.EncodeTime = zapcore.ISO8601TimeEncoder
var core zapcore.Core
if format == "console" {
core = zapcore.NewCore(
zapcore.NewConsoleEncoder(encoderCfg),
zapcore.AddSync(os.Stdout),
lvl,
)
} else {
core = zapcore.NewCore(
zapcore.NewJSONEncoder(encoderCfg),
zapcore.AddSync(os.Stdout),
lvl,
)
}
logger := zap.New(core, zap.AddCaller(), zap.AddStacktrace(zapcore.ErrorLevel))
Log = logger.Sugar()
}
// Sync 刷新缓冲区,退出前调用。
func Sync() {
if Log != nil {
_ = Log.Sync()
}
}