package logger import ( "go.uber.org/zap" "go.uber.org/zap/zapcore" "gopkg.in/natefinch/lumberjack.v2" "log" "os" "strings" ) var ( zapLogger *zap.Logger zapSug *zap.SugaredLogger ) var levelMap = map[string]zapcore.Level{ "debug": zapcore.DebugLevel, "info": zapcore.InfoLevel, "warn": zapcore.WarnLevel, "error": zapcore.ErrorLevel, "dpanic": zapcore.DPanicLevel, "panic": zapcore.PanicLevel, "fatal": zapcore.FatalLevel, } type Config struct { Filename string Console bool MaxSize int // megabytes MaxBackups int MaxAge int //days Compress bool // disabled by default Level string } func Init(conf *Config) { ws := make([]zapcore.WriteSyncer, 0) if conf.Console || conf.Filename == "" { ws = append(ws, zapcore.AddSync(os.Stdout)) } if conf.Filename != "" { s := &lumberjack.Logger{ Filename: conf.Filename, MaxSize: conf.MaxSize, // 拆分大小, megabytes MaxBackups: conf.MaxBackups, MaxAge: conf.MaxAge, //days Compress: conf.Compress, // disabled by default } ws = append(ws, zapcore.AddSync(s)) } var level zapcore.Level if v, ok := levelMap[strings.ToLower(conf.Level)]; ok { level = v } else { level = zapcore.DebugLevel } zapLogger, zapSug = NewLogger(level, ws...) } func NewLogger(level zapcore.Level, ws ...zapcore.WriteSyncer) (l *zap.Logger, s *zap.SugaredLogger) { cfg := zap.NewProductionEncoderConfig() //cfg.EncodeTime = zapcore.ISO8601TimeEncoder cfg.EncodeTime = zapcore.TimeEncoderOfLayout("2006-01-02 15:04:05") cfg.EncodeLevel = zapcore.CapitalColorLevelEncoder encoder := zapcore.NewConsoleEncoder(cfg) core := zapcore.NewCore(encoder, zapcore.NewMultiWriteSyncer(ws...), level) l = zap.New(zapcore.NewTee(core), zap.AddCaller()) s = l.Sugar() return } func GetStdLog() *log.Logger { return zap.NewStdLog(zapLogger) } func With(args ...interface{}) *zap.SugaredLogger { return zapSug.With(args...) } func Debug(args ...interface{}) { zapSug.Debug(args...) } func Info(args ...interface{}) { zapSug.Info(args...) } func Warn(args ...interface{}) { zapSug.Warn(args...) } func Error(args ...interface{}) { zapSug.Error(args...) } func Fatal(args ...interface{}) { zapSug.Fatal(args...) } func Debugf(format string, args ...interface{}) { zapSug.Debugf(format, args...) } // Infof Printf calls Output to print to the standard logger. // Arguments are handled in the manner of fmt.Printf. func Infof(format string, args ...interface{}) { zapSug.Infof(format, args...) } func Warnf(format string, args ...interface{}) { zapSug.Warnf(format, args...) } func Errorf(format string, args ...interface{}) { zapSug.Errorf(format, args...) } func Fatalf(format string, args ...interface{}) { zapSug.Fatalf(format, args...) } func Flush() { zapLogger.Sync() zapSug.Sync() }