github.com/GuanceCloud/cliutils@v1.1.21/logger/customize_output.go (about) 1 // Unless explicitly stated otherwise all files in this repository are licensed 2 // under the MIT License. 3 // This product includes software developed at Guance Cloud (https://www.guance.com/). 4 // Copyright 2021-present Guance, Inc. 5 6 package logger 7 8 import ( 9 "io" 10 "strings" 11 12 "go.uber.org/zap" 13 "go.uber.org/zap/zapcore" 14 ) 15 16 func newCustomizeRootLogger(level string, options int, ws io.Writer) (*zap.Logger, error) { 17 // use lumberjack.Logger for rotate 18 w := zapcore.AddSync(ws) 19 20 cfg := zapcore.EncoderConfig{ 21 NameKey: NameKeyMod, 22 MessageKey: NameKeyMsg, 23 LevelKey: NameKeyLevel, 24 TimeKey: NameKeyTime, 25 CallerKey: NameKeyPos, 26 27 EncodeLevel: zapcore.CapitalLevelEncoder, 28 EncodeTime: zapcore.ISO8601TimeEncoder, 29 EncodeCaller: zapcore.FullCallerEncoder, 30 } 31 32 if options&OPT_COLOR != 0 { 33 cfg.EncodeLevel = zapcore.CapitalColorLevelEncoder 34 } 35 36 if options&OPT_SHORT_CALLER != 0 { 37 cfg.EncodeCaller = zapcore.ShortCallerEncoder 38 } 39 40 var enc zapcore.Encoder 41 if options&OPT_ENC_CONSOLE != 0 { 42 enc = zapcore.NewConsoleEncoder(cfg) 43 } else { 44 enc = zapcore.NewJSONEncoder(cfg) 45 } 46 47 var lvl zapcore.Level 48 switch strings.ToLower(level) { 49 case INFO: // pass 50 lvl = zap.InfoLevel 51 case DEBUG: 52 lvl = zap.DebugLevel 53 case WARN: 54 lvl = zap.WarnLevel 55 case ERROR: 56 lvl = zap.ErrorLevel 57 case PANIC: 58 lvl = zap.PanicLevel 59 case DPANIC: 60 lvl = zap.DPanicLevel 61 case FATAL: 62 lvl = zap.FatalLevel 63 default: 64 lvl = zap.DebugLevel 65 } 66 67 core := zapcore.NewCore(enc, w, lvl) 68 // NOTE: why need add another option while 69 // zapcore.ShortCallerEncoder/FullCallerEncoder been set 70 l := zap.New(core, zap.AddCaller()) 71 return l, nil 72 } 73 74 func newOnlyMessageRootLogger(ws io.Writer) (*zap.Logger, error) { 75 // use lumberjack.Logger for rotate 76 w := zapcore.AddSync(ws) 77 78 cfg := zapcore.EncoderConfig{ 79 MessageKey: NameKeyMsg, 80 81 EncodeLevel: zapcore.CapitalLevelEncoder, 82 EncodeTime: zapcore.ISO8601TimeEncoder, 83 EncodeCaller: zapcore.FullCallerEncoder, 84 } 85 86 enc := zapcore.NewConsoleEncoder(cfg) 87 lvl := zap.DebugLevel 88 89 core := zapcore.NewCore(enc, w, lvl) 90 // NOTE: why need add another option while 91 // zapcore.ShortCallerEncoder/FullCallerEncoder been set 92 l := zap.New(core, zap.AddCaller()) 93 return l, nil 94 }