github.com/machinefi/w3bstream@v1.6.5-rc9.0.20240426031326-b8c7c4876e72/pkg/depends/kit/logr/slog/log.go (about) 1 package slog 2 3 import ( 4 "context" 5 "fmt" 6 "log/slog" 7 "strings" 8 9 "github.com/machinefi/w3bstream/pkg/depends/kit/logr" 10 ) 11 12 func Logger(l *slog.Logger) logr.Logger { 13 return &logger{slog: l} 14 } 15 16 type logger struct { 17 ctx context.Context 18 slog *slog.Logger 19 spans []string 20 } 21 22 var _ logr.Logger = (*logger)(nil) 23 24 func (d *logger) WithValues(kvs ...any) logr.Logger { 25 return &logger{ 26 spans: d.spans, 27 slog: d.slog.With(kvs...), 28 } 29 } 30 31 func (d *logger) Start(ctx context.Context, name string, kvs ...any) (context.Context, logr.Logger) { 32 spans := append(d.spans, name) 33 34 if len(kvs) == 0 { 35 return ctx, &logger{ 36 ctx: ctx, 37 spans: spans, 38 slog: d.slog.WithGroup(strings.Join(spans, "/")), 39 } 40 } 41 42 return ctx, &logger{ 43 spans: spans, 44 slog: d.slog.WithGroup(strings.Join(spans, "/")).With(kvs...), 45 } 46 } 47 48 func (d *logger) End() { 49 if len(d.spans) != 0 { 50 d.spans = d.spans[0 : len(d.spans)-1] 51 } 52 } 53 54 func (d *logger) Debug(format string, args ...any) { 55 if !d.slog.Enabled(d.ctx, slog.LevelDebug) { 56 return 57 } 58 d.slog.Log(d.ctx, slog.LevelDebug, fmt.Sprintf(format, args...)) 59 } 60 61 func (d *logger) Info(format string, args ...any) { 62 if !d.slog.Enabled(d.ctx, slog.LevelInfo) { 63 return 64 } 65 d.slog.Log(d.ctx, slog.LevelInfo, fmt.Sprintf(format, args...)) 66 } 67 68 func (d *logger) Warn(err error) { 69 if !d.slog.Enabled(d.ctx, slog.LevelWarn) { 70 return 71 } 72 d.slog.Log(d.ctx, slog.LevelWarn, err.Error(), slog.Any("err", err)) 73 } 74 75 func (d *logger) Error(err error) { 76 d.slog.Error(err.Error()) 77 }