1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79
| package logger
import ( "mywork/demo/internal/config" "os" "strings" "time" "go.uber.org/zap" "go.uber.org/zap/zapcore" "gopkg.in/natefinch/lumberjack.v2" )
var ZapLogger *zap.Logger var SugarLogger *zap.SugaredLogger
func InitLogger() {
logWriter := []zapcore.WriteSyncer{zapcore.AddSync(os.Stdout)}
if config.Configuration.Logger.File != "" { hook := setFileWriter(config.Configuration.Logger.File) logWriter = append(logWriter, hook) } encoderConfig := setEncoder()
level := getLogLevel(config.Configuration.Logger.Level)
core := zapcore.NewCore(encoderConfig, zapcore.NewMultiWriteSyncer(logWriter...), level)
ZapLogger = zap.New(core, zap.AddCaller()) ZapLogger.Info("ZapLogger", zap.String("String", "ohoh"), zap.Int("Int", 3), zap.Duration("backoff", time.Second), ) SugarLogger = ZapLogger.Sugar()
}
func setEncoder() zapcore.Encoder { encoderConfig := zap.NewProductionEncoderConfig() encoderConfig.EncodeTime = zapcore.ISO8601TimeEncoder encoderConfig.EncodeLevel = zapcore.CapitalLevelEncoder return zapcore.NewConsoleEncoder(encoderConfig) }
func setFileWriter(filePath string) zapcore.WriteSyncer { lumberJackLogger := &lumberjack.Logger{ Filename: filePath, MaxSize: 1, MaxBackups: 5, MaxAge: 30, Compress: false, } return zapcore.AddSync(lumberJackLogger) }
func getLogLevel(lv string) zapcore.Level { lv = strings.ToLower(lv) if level, ok := levelMap[lv]; ok { return level } return zapcore.InfoLevel }
var levelMap = map[string]zapcore.Level{ "debug": zapcore.DebugLevel, "info": zapcore.InfoLevel, "warn": zapcore.WarnLevel, "error": zapcore.ErrorLevel, }
|