golang 使用 zap logger 加入Lumberjack 写日志
Cd 进入项目目录
go get go.uber.org/zap/zapcore
go get -u github.com/natefinch/lumberjack
关于下面代码说明:
func getLogWriter() zapcore.WriteSyncer { lumberJackLogger := &lumberjack.Logger{ Filename: "../logs/log.log", // 日志文件的位置 MaxSize: 1, // 在进行切割之前,日志文件的最大大小(以MB为单位) MaxBackups: 5, // 保留旧文件的最大个数 MaxAge: 30, // 保留旧文件的最大天数 Compress: false, // 是否压缩/归档旧文件 } return zapcore.AddSync(lumberJackLogger) }
具体实现代码
package main import ( "net/http" "github.com/natefinch/lumberjack" "go.uber.org/zap" "go.uber.org/zap/zapcore" ) var sugarLogger *zap.SugaredLogger func main() { InitLogger() defer sugarLogger.Sync() simpleHttpGet("www.topgoer.com") simpleHttpGet("http://www.topgoer.com") } func InitLogger() { writeSyncer := getLogWriter() encoder := getEncoder() core := zapcore.NewCore(encoder, writeSyncer, zapcore.DebugLevel) logger := zap.New(core, zap.AddCaller()) sugarLogger = logger.Sugar() } func getEncoder() zapcore.Encoder { encoderConfig := zap.NewProductionEncoderConfig() encoderConfig.EncodeTime = zapcore.ISO8601TimeEncoder encoderConfig.EncodeLevel = zapcore.CapitalLevelEncoder return zapcore.NewConsoleEncoder(encoderConfig) } func getLogWriter() zapcore.WriteSyncer { lumberJackLogger := &lumberjack.Logger{ Filename: "./test.log", MaxSize: 1, MaxBackups: 5, MaxAge: 30, Compress: false, } return zapcore.AddSync(lumberJackLogger) } func simpleHttpGet(url string) { sugarLogger.Debugf("Trying to hit GET request for %s", url) resp, err := http.Get(url) if err != nil { sugarLogger.Errorf("Error fetching URL %s : Error = %s", url, err) } else { sugarLogger.Infof("Success! statusCode = %s for URL %s", resp.Status, url) resp.Body.Close() } }
标签:zapcore,Lumberjack,golang,func,go,logger,sugarLogger,zap From: https://www.cnblogs.com/yingger/p/18231525