-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlogger.go
More file actions
80 lines (66 loc) · 1.58 KB
/
logger.go
File metadata and controls
80 lines (66 loc) · 1.58 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
package logs
import (
"context"
"go.opentelemetry.io/otel/trace"
"log/slog"
"strings"
)
type Handler struct {
slog.Handler
}
// ParseLevel parses a level string.
func ParseLevel(level string) slog.Level {
switch strings.ToLower(level) {
case "debug":
return slog.LevelDebug
case "info":
return slog.LevelInfo
case "warn":
return slog.LevelWarn
case "error":
return slog.LevelError
default:
return slog.LevelInfo
}
}
// WrapHandler wraps a slog.Handler.
func WrapHandler(handler slog.Handler) *Handler {
h := &Handler{
Handler: handler,
}
return h
}
// Enabled implements slog.Handler.
func (h *Handler) Enabled(ctx context.Context, level slog.Level) bool {
return h.Handler.Enabled(ctx, level)
}
// WithGroup implements slog.Handler.
func (h *Handler) WithGroup(name string) slog.Handler {
clone := *h
clone.Handler = h.Handler.WithGroup(name)
return &clone
}
// WithAttrs implements slog.Handler.
func (h *Handler) WithAttrs(attrs []slog.Attr) slog.Handler {
clone := *h
clone.Handler = h.Handler.WithAttrs(attrs)
return &clone
}
// Handle implements slog.Handler.
func (h *Handler) Handle(ctx context.Context, r slog.Record) error {
if !h.Handler.Enabled(ctx, r.Level) {
return h.Handler.Handle(ctx, r)
}
var attrs []slog.Attr
spanCtx := trace.SpanContextFromContext(ctx)
if spanCtx.HasTraceID() {
attrs = append(attrs, slog.String("trace", spanCtx.TraceID().String()))
}
if spanCtx.HasSpanID() {
attrs = append(attrs, slog.String("span", spanCtx.SpanID().String()))
}
if len(attrs) > 0 {
r.AddAttrs(attrs...)
}
return h.Handler.Handle(ctx, r)
}