// Copyright 2019 github.com. All rights reserved. // Use of this source code is governed by github.com. package logger import ( "strings" "time" "go.uber.org/zap" "go.uber.org/zap/zapcore" "gopkg.in/natefinch/lumberjack.v2" ) // zapConfig 用于对zap进行配置的参数 type zapConfig struct { Level zap.AtomicLevel `json:"level" yaml:"level"` Development bool `json:"development" yaml:"development"` DisableCaller bool `json:"disableCaller" yaml:"disableCaller"` DisableStacktrace bool `json:"disableStacktrace" yaml:"disableStacktrace"` Encoding string `json:"encoding" yaml:"encoding"` OutputPath string `json:"outputPath" yaml:"outputPath"` } // New 创建logger func (zc *zapConfig) New(maxSize, maxBackups, maxAge int) *zap.Logger { // if nil, default the values if maxSize == 0 { maxSize = 100 } if maxBackups == 0 { maxBackups = 7 } if maxAge == 0 { maxAge = 30 } hook := lumberjack.Logger{ Filename: zc.OutputPath, MaxSize: maxSize, // megabytes MaxBackups: maxBackups, // backups number MaxAge: maxAge, // days Compress: true, // disabled by default } fileWriter := zapcore.AddSync(&hook) var encoderConfig zapcore.EncoderConfig if zc.Development { encoderConfig = zap.NewDevelopmentEncoderConfig() } else { encoderConfig = zap.NewProductionEncoderConfig() } // 自定义 encoderConfig.EncodeTime = CustomTimeEncoder var encoder zapcore.Encoder if strings.ToLower(zc.Encoding) == "console" { encoder = zapcore.NewConsoleEncoder(encoderConfig) } else { encoder = zapcore.NewJSONEncoder(encoderConfig) } core := zapcore.NewCore(encoder, fileWriter, zc.Level) opts := zc.buildOptions(fileWriter) return zap.New(core, opts...) } func (zc *zapConfig) buildOptions(fileWriter zapcore.WriteSyncer) []zap.Option { opts := []zap.Option{zap.ErrorOutput(fileWriter)} if !zc.DisableCaller { opts = append(opts, zap.AddCaller()) } if !zc.DisableStacktrace { stackLevel := zap.ErrorLevel if zc.Development { stackLevel = zap.WarnLevel } opts = append(opts, zap.AddStacktrace(stackLevel)) } return opts } // 自定义时间格式 func CustomTimeEncoder(t time.Time, enc zapcore.PrimitiveArrayEncoder) { enc.AppendString(t.Format("2006-01-02 15:04:05.000")) }