玩转高性能日志库ZAP (2)
版权声明 本站原创文章 由 萌叔 发表 转载请注明 萌叔 | http://vearne.cc 前言 uber开源的高性能日志库zap, 除了性能远超logrus之外,还有很多诱人的功能,比如支持日志采样、支持通过HTTP服务动态调整日志级别。不过他原生不支持文件归档,如果要支持文件按大小或者时间归档,必须要使用第三方库, 根据官方资料参考资料1,官方推荐的是 natefinch/lumberjack 示例 package main import ( "go.uber.org/zap" "go.uber.org/zap/zapcore" "gopkg.in/natefinch/lumberjack.v2" ) // logpath 日志文件路径 // loglevel 日志级别 func initLogger(logpath string, loglevel string) *zap.Logger { hook := lumberjack.Logger{ Filename: logpath, // 日志文件路径 MaxSize: 1024, // megabytes MaxBackups: 3, // 最多保留3个备份 MaxAge: 7, //days Compress: true, // 是否压缩 disabled by default } w := zapcore.AddSync(&hook) var level zapcore.Level switch loglevel { case "debug": level = zap.DebugLevel case "info": level = zap.InfoLevel case "error": level = zap.ErrorLevel default: level = zap.InfoLevel } encoderConfig := zap.NewProductionEncoderConfig() encoderConfig.EncodeTime = zapcore.ISO8601TimeEncoder core := zapcore.NewCore( zapcore.NewConsoleEncoder(encoderConfig), w, level, ) logger := zap.New(core) logger.Info("DefaultLogger init success") return logger } func main() { logger := initLogger("/tmp/all.log", "info") logger.Info("test log", zap.Int("line", 47)) } 文件的清理策略如下 Cleaning Up Old Log Files Whenever a new logfile gets created, old log files may be deleted. The most recent files according to the encoded timestamp will be retained, up to a number equal to MaxBackups (or all of them if MaxBackups is 0). Any files with an encoded timestamp older than MaxAge days are deleted, regardless of MaxBackups. Note that the time encoded in the timestamp is the rotation time, which may differ from the last time that file was written to. ...