1.前言
zap 是我个人比较喜欢的日志库,是 uber 开源的,有较好的性能。很多开源 Go 项目都使用它作为日志组件。
2.安装使用
安装
go get -u go.uber.org/zap
快速入门
logger, _ := zap.NewProduction()
defer logger.Sync() // flushes buffer, if any
sugar := logger.Sugar()
sugar.Infow("failed to fetch URL",
// Structured context as loosely typed key-value pairs.
"url", url,
"attempt", 3,
"backoff", time.Second,
)
sugar.Infof("Failed to fetch URL: %s", url)
3.进阶
这里介绍一些我常用的配置方式。
自定义时间格式
customTimeEncoder := func(t time.Time, enc zapcore.PrimitiveArrayEncoder) {
enc.AppendString(t.Format("2006-01-02 15:04:05.000"))
}
自定义日志级别显示
customLevelEncoder := func(level zapcore.Level, enc zapcore.PrimitiveArrayEncoder) {
enc.AppendString(level.CapitalString())
}
自定义代码路径、行号输出
customCallerEncoder := func(caller zapcore.EntryCaller, enc zapcore.PrimitiveArrayEncoder) {
enc.AppendString("[" + caller.TrimmedPath() + "]")
}
构建配置
zapLoggerEncoderConfig := zapcore.EncoderConfig{
TimeKey: "time",
LevelKey: "level",
NameKey: "logger",
CallerKey: "caller",
MessageKey: "message",
StacktraceKey: "stacktrace",
EncodeCaller: customCallerEncoder,
EncodeTime: customTimeEncoder,
EncodeLevel: customLevelEncoder,
EncodeDuration: zapcore.SecondsDurationEncoder,
LineEnding: "\n",
ConsoleSeparator: " ",
}
控制台输出配置(带颜色)
zapLoggerEncoderConfig.EncodeLevel = zapcore.CapitalColorLevelEncoder
syncWriter = zapcore.NewMultiWriteSyncer(zapcore.AddSync(os.Stdout))
输出到文件
syncWriter = zapcore.NewMultiWriteSyncer(zapcore.AddSync(os.Stdout), zapcore.AddSync(&lumberjack.Logger{
Filename: "logs/app/app.log", // ⽇志⽂件路径
MaxSize: 100, // 单位为MB,默认为512MB
MaxAge: 5, // 文件最多保存多少天
LocalTime: true, // 采用本地时间
Compress: false, // 是否压缩日志
}))
lumberjack 需要自己安装
go get gopkg.in/natefinch/lumberjack.v2
异步输出到文件
syncWriter = &zapcore.BufferedWriteSyncer{
WS: zapcore.AddSync(&lumberjack.Logger{
Filename: "logs/app/app.log", // ⽇志⽂件路径
MaxSize: 100, // 单位为MB,默认为512MB
MaxAge: 5, // 文件最多保存多少天
LocalTime: true, // 采用本地时间
Compress: false, // 是否压缩日志
}),
Size: 4096,
}
构建 logger
zapCore := zapcore.NewCore(zapcore.NewConsoleEncoder(zapLoggerEncoderConfig), syncWriter, level)
zapLogger = zap.New(zapCore, zap.AddCaller(), zap.AddCallerSkip(1))
记得在程序退出时调用 zapLogger.Sync()
,不然会造成丢失日志。
效果
标签:zapcore,enc,syncWriter,Go,日志,logger,zap From: https://www.cnblogs.com/stulzq/p/16741844.html