github.com/netdata/go.d.plugin@v0.58.1/logger/handler.go (about) 1 package logger 2 3 import ( 4 "context" 5 "log/slog" 6 "os" 7 "runtime" 8 "strings" 9 10 "github.com/lmittmann/tint" 11 ) 12 13 func newTextHandler() slog.Handler { 14 return slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{ 15 Level: Level.lvl, 16 ReplaceAttr: func(groups []string, a slog.Attr) slog.Attr { 17 if a.Key == slog.TimeKey && isJournal { 18 return slog.Attr{} 19 } 20 if a.Key == slog.LevelKey { 21 v := a.Value.Any().(slog.Level) 22 a.Value = slog.StringValue(strings.ToLower(v.String())) 23 } 24 return a 25 }, 26 }) 27 } 28 29 func newTerminalHandler() slog.Handler { 30 return tint.NewHandler(os.Stderr, &tint.Options{ 31 AddSource: true, 32 Level: Level.lvl, 33 ReplaceAttr: func(groups []string, a slog.Attr) slog.Attr { 34 if a.Key == slog.TimeKey { 35 return slog.Attr{} 36 } 37 if a.Key == slog.SourceKey && !Level.Enabled(slog.LevelDebug) { 38 return slog.Attr{} 39 } 40 return a 41 }, 42 }) 43 } 44 45 func withCallDepth(depth int, sh slog.Handler) slog.Handler { 46 if v, ok := sh.(*callDepthHandler); ok { 47 sh = v.sh 48 } 49 return &callDepthHandler{depth: depth, sh: sh} 50 } 51 52 type callDepthHandler struct { 53 depth int 54 sh slog.Handler 55 } 56 57 func (h *callDepthHandler) Enabled(ctx context.Context, level slog.Level) bool { 58 return h.sh.Enabled(ctx, level) 59 } 60 61 func (h *callDepthHandler) WithAttrs(attrs []slog.Attr) slog.Handler { 62 return withCallDepth(h.depth, h.sh.WithAttrs(attrs)) 63 } 64 65 func (h *callDepthHandler) WithGroup(name string) slog.Handler { 66 return withCallDepth(h.depth, h.sh.WithGroup(name)) 67 } 68 69 func (h *callDepthHandler) Handle(ctx context.Context, r slog.Record) error { 70 // https://pkg.go.dev/log/slog#example-package-Wrapping 71 var pcs [1]uintptr 72 // skip Callers and this function 73 runtime.Callers(h.depth+2, pcs[:]) 74 r.PC = pcs[0] 75 76 return h.sh.Handle(ctx, r) 77 }