/* * @Date: 2021-03-22 10:13:04 * @LastEditors: viletyy * @LastEditTime: 2021-06-10 15:44:06 * @FilePath: /potato/initialize/zap.go */ package initialize import ( "fmt" "time" "github.com/viletyy/potato/global" "github.com/viletyy/potato/pkg" "github.com/viletyy/yolk/directory" "go.uber.org/zap" "go.uber.org/zap/zapcore" ) var level zapcore.Level func Zap() (logger *zap.Logger) { if err := directory.CreateDir(global.GO_CONFIG.Zap.Director); err != nil { fmt.Printf("Create Zap Dir err:%v", err.Error()) } switch global.GO_CONFIG.Zap.Level { case "debug": level = zap.DebugLevel case "info": level = zap.InfoLevel case "warn": level = zap.WarnLevel case "error": level = zap.ErrorLevel case "dpanic": level = zap.DPanicLevel case "panic": level = zap.PanicLevel case "fatal": level = zap.FatalLevel default: level = zap.InfoLevel } if level == zap.DebugLevel || level == zap.ErrorLevel { logger = zap.New(getEncoderCore(), zap.AddStacktrace(level)) } else { logger = zap.New(getEncoderCore()) } if global.GO_CONFIG.Zap.ShowLine { logger = logger.WithOptions(zap.AddCaller()) } return logger } func getEncoderCore() (core zapcore.Core) { writer, err := pkg.GetWriteSyncer() // 使用file-rotatelogs进行日志分割 if err != nil { fmt.Printf("Get Write Syncer Failed err: %v", err.Error()) return } return zapcore.NewCore(getEncoder(), writer, level) } func getEncoder() zapcore.Encoder { if global.GO_CONFIG.Zap.Format == "json" { return zapcore.NewJSONEncoder(getEncoderConfig()) } return zapcore.NewConsoleEncoder(getEncoderConfig()) } func getEncoderConfig() (config zapcore.EncoderConfig) { config = zapcore.EncoderConfig{ MessageKey: "message", LevelKey: "level", TimeKey: "time", NameKey: "logger", CallerKey: "caller", StacktraceKey: global.GO_CONFIG.Zap.StacktraceKey, LineEnding: zapcore.DefaultLineEnding, EncodeLevel: zapcore.LowercaseLevelEncoder, EncodeTime: CustomTimeEncoder, EncodeDuration: zapcore.SecondsDurationEncoder, EncodeCaller: zapcore.FullCallerEncoder, } switch { case global.GO_CONFIG.Zap.EncodeLevel == "LowercaseLevelEncoder": // 小写编码器(默认) config.EncodeLevel = zapcore.LowercaseLevelEncoder case global.GO_CONFIG.Zap.EncodeLevel == "LowercaseColorLevelEncoder": // 小写编码器带颜色 config.EncodeLevel = zapcore.LowercaseColorLevelEncoder case global.GO_CONFIG.Zap.EncodeLevel == "CapitalLevelEncoder": // 大写编码器 config.EncodeLevel = zapcore.CapitalLevelEncoder case global.GO_CONFIG.Zap.EncodeLevel == "CapitalColorLevelEncoder": // 大写编码器带颜色 config.EncodeLevel = zapcore.CapitalColorLevelEncoder default: config.EncodeLevel = zapcore.LowercaseLevelEncoder } return config } func CustomTimeEncoder(t time.Time, enc zapcore.PrimitiveArrayEncoder) { enc.AppendString(t.Format(global.GO_CONFIG.Zap.Prefix + "2006/01/02 - 15:04:05.000")) }