Go:zap log rotate(日志轮转)
Demo:
package main
import (
"go.uber.org/zap"
"go.uber.org/zap/zapcore"
"gopkg.in/natefinch/lumberjack.v2"
)
func main() {
// 日志级别
logLevel := "DEBUG"
atomicLevel := zap.NewAtomicLevel()
switch logLevel {
case "DEBUG":
atomicLevel.SetLevel(zapcore.DebugLevel)
case "INFO":
atomicLevel.SetLevel(zapcore.InfoLevel)
case "WARN":
atomicLevel.SetLevel(zapcore.WarnLevel)
case "ERROR":
atomicLevel.SetLevel(zapcore.ErrorLevel)
case "DPANIC":
atomicLevel.SetLevel(zapcore.DPanicLevel)
case "PANIC":
atomicLevel.SetLevel(zapcore.PanicLevel)
case "FATAL":
atomicLevel.SetLevel(zapcore.FatalLevel)
}
encoderConfig := zapcore.EncoderConfig{
TimeKey: "time",
LevelKey: "level",
NameKey: "name",
CallerKey: "line",
MessageKey: "msg",
FunctionKey: "func",
StacktraceKey: "stacktrace",
LineEnding: zapcore.DefaultLineEnding,
EncodeLevel: zapcore.LowercaseLevelEncoder,
EncodeTime: zapcore.ISO8601TimeEncoder,
EncodeDuration: zapcore.SecondsDurationEncoder,
EncodeCaller: zapcore.FullCallerEncoder,
EncodeName: zapcore.FullNameEncoder,
}
// 日志轮转
writer := &lumberjack.Logger{
// 日志名称
Filename: "test1280.log",
// 日志大小限制,单位MB
MaxSize: 100,
// 历史日志文件保留天数
MaxAge: 30,
// 最大保留历史日志数量
MaxBackups: 10,
// 本地时区
LocalTime: true,
// 历史日志文件压缩标识
Compress: false,
}
zapCore := zapcore.NewCore(
zapcore.NewJSONEncoder(encoderConfig),
zapcore.AddSync(writer),
atomicLevel,
)
logger := zap.New(zapCore, zap.AddCaller())
defer logger.Sync()
logger.Sugar().Debug("test1280's debug")
logger.Sugar().Infof("test1280's %s", "infof")
logger.Sugar().Warnf("test1280's %s", "warnf")
logger.Sugar().Error("test1280's error")
}
执行:
EB@DESKTOP-K45IA6V MINGW64 ~/Desktop/test1280
$ go run main.go
结果:
EB@DESKTOP-K45IA6V MINGW64 ~/Desktop/test1280
$ cat test1280.log
{"level":"debug","time":"2021-05-25T22:23:44.846+0800","line":"C:/Users/EB/Desktop/test1280/main.go:71","func":"main.main","msg"
:"test1280's debug"}
{"level":"info","time":"2021-05-25T22:23:44.863+0800","line":"C:/Users/EB/Desktop/test1280/main.go:72","func":"main.main","msg":
"test1280's infof"}
{"level":"warn","time":"2021-05-25T22:23:44.863+0800","line":"C:/Users/EB/Desktop/test1280/main.go:73","func":"main.main","msg":
"test1280's warnf"}
{"level":"error","time":"2021-05-25T22:23:44.863+0800","line":"C:/Users/EB/Desktop/test1280/main.go:74","func":"main.main","msg"
:"test1280's error"}
原生zap不提供log rotate日志轮转功能,依赖于第三方库lumberjack:
https://github.com/natefinch/lumberjack
本Demo日志轮转核心代码:
// 日志轮转
writer := &lumberjack.Logger{
// 日志名称
Filename: "test1280.log",
// 日志大小限制,单位MB
MaxSize: 100,
// 历史日志文件保留天数
MaxAge: 30,
// 最大保留历史日志数量
MaxBackups: 10,
// 本地时区
LocalTime: true,
// 历史日志文件压缩标识
Compress: false,
}
......
zapCore := zapcore.NewCore(
...
zapcore.AddSync(writer),
...
)
参考:
1.https://github.com/natefinch/lumberjack
2.https://github.com/uber-go/zap
3.https://pkg.go.dev/go.uber.org/zap
4.https://studygolang.com/articles/32205?fr=sidebar