github.com/iotexproject/iotex-core@v1.14.1-rc1/pkg/log/tracelog.go (about) 1 package log 2 3 import ( 4 "context" 5 "fmt" 6 7 "github.com/uptrace/opentelemetry-go-extra/otelzap" 8 "go.uber.org/zap" 9 "go.uber.org/zap/zapcore" 10 ) 11 12 var ( 13 _traceLogger = otelzap.New(zap.NewNop()) 14 ) 15 16 // T is a wrapper of otelzap.Ctx, returns a logger with context. 17 func T(ctx context.Context) otelzap.LoggerWithCtx { 18 return _traceLogger.Ctx(ctx) 19 } 20 21 // TraceConfig defines the logger configurations for tracing. 22 type TraceConfig struct { 23 MinLevel string `json:"minLevel" yaml:"minLevel"` 24 ErrorStatusLevel string `json:"errorStatusLevel" yaml:"errorStatusLevel"` 25 Caller bool `json:"caller" yaml:"caller"` 26 CallerDepth int `json:"callerDepth" yaml:"callerDepth"` 27 StackTrace bool `json:"stackTrace" yaml:"stackTrace"` 28 WithTraceID bool `json:"withTraceID" yaml:"withTraceID"` 29 } 30 31 func initTraceLogger(logger *zap.Logger, cfg *TraceConfig) error { 32 opts, err := parseTraceConfig(cfg) 33 if err != nil { 34 return err 35 } 36 _traceLogger = otelzap.New(logger, opts...) 37 return nil 38 } 39 40 func parseTraceConfig(cfg *TraceConfig) ([]otelzap.Option, error) { 41 var opts []otelzap.Option 42 if cfg == nil { 43 return opts, nil 44 } 45 if cfg.MinLevel != "" { 46 var level zapcore.Level 47 if err := level.UnmarshalText([]byte(cfg.MinLevel)); err != nil { 48 return nil, fmt.Errorf("invalid minLevel: %w", err) 49 } 50 opts = append(opts, otelzap.WithMinLevel(level)) 51 } 52 if cfg.ErrorStatusLevel != "" { 53 var level zapcore.Level 54 if err := level.UnmarshalText([]byte(cfg.ErrorStatusLevel)); err != nil { 55 return nil, fmt.Errorf("invalid errorStatusLevel: %w", err) 56 } 57 opts = append(opts, otelzap.WithErrorStatusLevel(level)) 58 } 59 if cfg.Caller { 60 opts = append(opts, otelzap.WithCaller(true)) 61 } 62 if cfg.CallerDepth > 0 { 63 opts = append(opts, otelzap.WithCallerDepth(cfg.CallerDepth)) 64 } 65 if cfg.StackTrace { 66 opts = append(opts, otelzap.WithStackTrace(true)) 67 } 68 if cfg.WithTraceID { 69 opts = append(opts, otelzap.WithTraceIDField(true)) 70 } 71 return opts, nil 72 }