星球狂想战队|Gin - 使用zap记录日志

简介
星球狂想战队|Gin - 使用zap记录日志zap是uber 开源的高性能日志库 , 面向高性能并且也确实做到了高性能 。
gin可以直接使用中间件来嵌入zap 。
星球狂想战队|Gin - 使用zap记录日志例子package main?import ("fmt""time"?ginzap "github.com/gin-contrib/zap""github.com/gin-gonic/gin""go.uber.org/zap")?func main() {r := gin.New()?logger, _ := zap.NewProduction()?// Add a ginzap middleware, which://- Logs all requests, like a combined access and error log.//- Logs to stdout.//- RFC3339 with UTC time format.r.Use(ginzap.Ginzap(logger, time.RFC3339, true))?// Logs all panic to error log//- stack means whether output the stack info.r.Use(ginzap.RecoveryWithZap(logger, true))?// Example ping request.r.GET("/now", func(c *gin.Context) {c.String(200, "现在时间:"+fmt.Sprint(time.Now()))})?// Example when panic happen.r.GET("/panic", func(c *gin.Context) {panic("An unexpected error happen!")})?// Listen and Server in 0.0.0.0:8080r.Run(":8080")}日志自动分割为了防止日志文件过大 , 我们可以设置日志文件分割 , 保留一个console特殊字段 , 用来在终端打印日志
package main?import ("os"?"go.uber.org/zap""go.uber.org/zap/zapcore""gopkg.in/natefinch/lumberjack.v2")?// InitLogger 初始化日志func InitLogger(logLeve string, filenames ...string) (logger *zap.Logger) {encoderConfig := zapcore.EncoderConfig{TimeKey:"time",LevelKey:"level",NameKey:"logger",CallerKey:"line",MessageKey:"msg",StacktraceKey:"stacktrace",LineEnding:zapcore.DefaultLineEnding,EncodeLevel:zapcore.LowercaseLevelEncoder, // 小写编码器EncodeTime:zapcore.ISO8601TimeEncoder,EncodeDuration: zapcore.SecondsDurationEncoder, //EncodeCaller:zapcore.FullCallerEncoder,// 短路径编码器EncodeName:zapcore.FullNameEncoder,}?// 设置日志级别atomicLevel := zap.NewAtomicLevel()switch logLeve {case "info":atomicLevel.SetLevel(zap.InfoLevel)case "debug":atomicLevel.SetLevel(zap.DebugLevel)case "warn":atomicLevel.SetLevel(zap.WarnLevel)case "error":atomicLevel.SetLevel(zap.ErrorLevel)default:atomicLevel.SetLevel(zap.InfoLevel)}writers := []zapcore.WriteSyncer{}if len(filenames) == 0 {writers = append(writers, zapcore.AddSync(os.Stdout))} else {for _, filename := range filenames {if filename == "console" || filename == "" {writers = append(writers, zapcore.AddSync(os.Stdout))continue}writers = append(writers, zapcore.AddSync(&lumberjack.Logger{Filename:filename, // 日志文件路径MaxSize:100,// 每个日志文件保存的最大尺寸 单位:MMaxBackups: 30,// 日志文件最多保存多少个备份MaxAge:30,// 文件最多保存多少天Compress:true,// 是否压缩}))}}core := zapcore.NewCore(// zapcore.NewJSONEncoder(encoderConfig), // 编码器配置zapcore.NewConsoleEncoder(encoderConfig), // 编码器配置zapcore.NewMultiWriteSyncer(writers...),// 打印到控制台和文件atomicLevel,// 日志级别)?// 开启开发模式 , 堆栈跟踪caller := zap.AddCaller()// 开启文件及行号development := zap.Development()// 设置初始化字段// filed := zap.Fields(// // zap.String("serviceName", "serviceName"),// )// 构造日志logger = zap.New(core, caller, development)return}