github.com/wfusion/gofusion@v1.1.14/log/utils.go (about) 1 package log 2 3 import ( 4 "strings" 5 6 "github.com/spf13/cast" 7 "go.uber.org/zap" 8 "go.uber.org/zap/zapcore" 9 10 "github.com/wfusion/gofusion/config" 11 "github.com/wfusion/gofusion/log/encoder" 12 ) 13 14 func getLogLevel(level string) zapcore.Level { 15 switch strings.ToLower(level) { 16 case "debug": 17 return zap.DebugLevel 18 case "info": 19 return zap.InfoLevel 20 case "warn": 21 return zap.WarnLevel 22 case "error": 23 return zap.ErrorLevel 24 case "panic": 25 return zap.PanicLevel 26 case "fatal": 27 return zap.FatalLevel 28 default: 29 return zap.InfoLevel 30 } 31 } 32 33 func getEncoderConfig(conf *Conf) zapcore.EncoderConfig { 34 skips := make([]string, 0, len(encoder.SkipCallers)+len(conf.SkipCallers)) 35 skips = append(skips, encoder.SkipCallers...) 36 skips = append(skips, conf.SkipCallers...) 37 return zapcore.EncoderConfig{ 38 LevelKey: "L", 39 TimeKey: "T", 40 MessageKey: "M", 41 NameKey: "N", 42 CallerKey: "C", 43 StacktraceKey: "S", 44 LineEnding: zapcore.DefaultLineEnding, 45 EncodeLevel: zapcore.CapitalLevelEncoder, 46 EncodeTime: zapcore.ISO8601TimeEncoder, 47 EncodeDuration: zapcore.SecondsDurationEncoder, 48 EncodeCaller: encoder.SkipCallerEncoder(skips, conf.ShorterFilepath), 49 } 50 } 51 52 func getEncoder(layout string, cfg zapcore.EncoderConfig) zapcore.Encoder { 53 switch strings.ToLower(layout) { 54 case "json": 55 return zapcore.NewJSONEncoder(cfg) 56 case "console": 57 return zapcore.NewConsoleEncoder(cfg) 58 default: 59 return zapcore.NewJSONEncoder(cfg) 60 } 61 } 62 63 func newZapLogLevel(appName, confName, enableField, levelField string) zapcore.LevelEnabler { 64 z := &zapLogLevel{ 65 enabled: true, 66 appName: config.Use(appName).AppName(), 67 confName: confName, 68 enableField: enableField, 69 levelField: levelField, 70 } 71 z.reloadConfig() 72 return z 73 } 74 75 type zapLogLevel struct { 76 zapcore.Level 77 78 enabled bool 79 appName string 80 confName string 81 enableField string 82 levelField string 83 } 84 85 func (z *zapLogLevel) Enabled(level zapcore.Level) bool { 86 if z.reloadConfig(); !z.enabled { 87 return false 88 } 89 90 return level >= z.Level 91 } 92 93 func (z *zapLogLevel) reloadConfig() { 94 var cfgs map[string]map[string]any 95 _ = config.Use(z.appName).LoadComponentConfig(config.ComponentLog, &cfgs) 96 if len(cfgs) == 0 { 97 return 98 } 99 100 cfg, ok := cfgs[z.confName] 101 if !ok { 102 return 103 } 104 enabled := cast.ToBool(cfg[z.enableField]) 105 z.enabled = enabled 106 107 logLevelObj, ok1 := cfg[z.levelField] 108 logLevel, ok2 := logLevelObj.(string) 109 if !ok1 || !ok2 { 110 return 111 } 112 level := getLogLevel(logLevel) 113 z.Level = level 114 }