github.com/wfusion/gofusion@v1.1.14/log/customlogger/routine.go (about) 1 package customlogger 2 3 import ( 4 "context" 5 "reflect" 6 7 "github.com/panjf2000/ants/v2" 8 "github.com/spf13/cast" 9 10 "github.com/wfusion/gofusion/config" 11 "github.com/wfusion/gofusion/log" 12 ) 13 14 var ( 15 // RoutineLoggerType FIXME: should not be deleted to avoid compiler optimized 16 RoutineLoggerType = reflect.TypeOf(routineLogger{}) 17 routineFields = log.Fields{"component": "routine"} 18 ) 19 20 func DefaultRoutineLogger() ants.Logger { 21 return &routineLogger{ 22 enabled: true, 23 } 24 } 25 26 type routineLogger struct { 27 log log.Loggable 28 appName string 29 enabled bool 30 } 31 32 func (r *routineLogger) Init(log log.Loggable, appName string) { 33 r.log = log 34 r.appName = appName 35 r.reloadConfig() 36 } 37 38 func (r *routineLogger) Printf(format string, args ...any) { 39 if r.reloadConfig(); r.enabled { 40 ctx, args := r.parseArgs(args...) 41 r.logger().Info(ctx, format, args...) 42 } 43 } 44 45 func (r *routineLogger) logger() log.Loggable { 46 if r.log != nil { 47 return r.log 48 } 49 return log.Use(config.DefaultInstanceKey, log.AppName(r.appName)) 50 } 51 52 func (r *routineLogger) parseArgs(args ...any) (ctx context.Context, params []any) { 53 var ok bool 54 55 if len(args) == 0 { 56 return context.Background(), []any{routineFields} 57 } 58 if len(args) == 1 { 59 args = append(args, routineFields) 60 return context.Background(), args 61 } 62 63 params = args 64 ctx, ok = args[0].(context.Context) 65 if ok { 66 params = args[1:] 67 } 68 69 if ctx == nil { 70 ctx = context.Background() 71 } 72 73 params = append(params, routineFields) 74 return 75 } 76 77 func (r *routineLogger) reloadConfig() { 78 cfg := make(map[string]any) 79 _ = config.Use(r.appName).LoadComponentConfig(config.ComponentGoroutinePool, &cfg) 80 81 r.enabled = cast.ToBool(cfg["enable_logger"]) 82 }