github.com/wfusion/gofusion@v1.1.14/log/customlogger/http.go (about) 1 package customlogger 2 3 import ( 4 "context" 5 "reflect" 6 "strings" 7 8 "github.com/go-resty/resty/v2" 9 "github.com/spf13/cast" 10 11 "github.com/wfusion/gofusion/config" 12 "github.com/wfusion/gofusion/log" 13 ) 14 15 var ( 16 HttpLoggerType = reflect.TypeOf(httpLogger{}) 17 httpFields = log.Fields{"component": strings.ToLower(config.ComponentHttp)} 18 ) 19 20 func DefaultHttpLogger() resty.Logger { 21 return new(httpLogger) 22 } 23 24 type httpLogger struct { 25 log log.Loggable 26 appName string 27 enabled bool 28 } 29 30 func (h *httpLogger) Init(log log.Loggable, appName string) { 31 h.log = log 32 h.appName = appName 33 h.reloadConfig() 34 } 35 36 func (h *httpLogger) Errorf(format string, v ...any) { 37 if h.reloadConfig(); h.enabled { 38 ctx, args := h.parseArgs(v...) 39 h.logger().Error(ctx, format, args...) 40 } 41 } 42 func (h *httpLogger) Warnf(format string, v ...any) { 43 if h.reloadConfig(); h.enabled { 44 ctx, args := h.parseArgs(v...) 45 h.logger().Info(ctx, format, args...) 46 } 47 } 48 func (h *httpLogger) Debugf(format string, v ...any) { 49 if h.reloadConfig(); h.enabled { 50 ctx, args := h.parseArgs(v...) 51 h.logger().Debug(ctx, format, args...) 52 } 53 } 54 55 func (h *httpLogger) logger() log.Loggable { 56 if h.log != nil { 57 return h.log 58 } 59 return log.Use(config.DefaultInstanceKey, log.AppName(h.appName)) 60 } 61 62 func (h *httpLogger) parseArgs(args ...any) (ctx context.Context, params []any) { 63 var ok bool 64 65 if len(args) == 0 { 66 return context.Background(), []any{httpFields} 67 } 68 if len(args) == 1 { 69 args = append(args, httpFields) 70 return context.Background(), args 71 } 72 73 params = args 74 ctx, ok = args[0].(context.Context) 75 if ok { 76 params = args[1:] 77 } 78 79 if ctx == nil { 80 ctx = context.Background() 81 } 82 83 params = append(params, httpFields) 84 return 85 } 86 87 func (h *httpLogger) reloadConfig() { 88 cfg := make(map[string]any) 89 _ = config.Use(h.appName).LoadComponentConfig(config.ComponentHttp, &cfg) 90 91 h.enabled = cast.ToBool(cfg["enable_logger"]) 92 }