github.com/machinefi/w3bstream@v1.6.5-rc9.0.20240426031326-b8c7c4876e72/pkg/depends/kit/logr/log.go (about) 1 package logr 2 3 import ( 4 "context" 5 6 "github.com/machinefi/w3bstream/pkg/depends/x/contextx" 7 ) 8 9 type Logger interface { 10 // Start to start span for tracing 11 // 12 // ctx log = log.Start(ctx, "SpanName") 13 // defer log.End() 14 // 15 Start(context.Context, string, ...any) (context.Context, Logger) 16 // End to end span 17 End() 18 19 // WithValues key value pairs 20 WithValues(keyAndValues ...interface{}) Logger 21 22 Debug(msg string, args ...interface{}) 23 Info(msg string, args ...interface{}) 24 Warn(err error) 25 Error(err error) 26 } 27 28 type keyLogger struct{} 29 30 func WithLogger(ctx context.Context, l Logger) context.Context { 31 return contextx.WithValue(ctx, keyLogger{}, l) 32 } 33 34 func WithLoggerContext(l Logger) contextx.WithContext { 35 return func(ctx context.Context) context.Context { 36 return WithLogger(ctx, l) 37 } 38 } 39 40 func FromContext(ctx context.Context) Logger { 41 if v, ok := ctx.Value(keyLogger{}).(Logger); ok { 42 return v 43 } 44 return Discard() 45 } 46 47 func Start(ctx context.Context, name string, kvs ...any) (context.Context, Logger) { 48 return FromContext(ctx).Start(ctx, name, kvs...) 49 }