/
otel_slog_handler.go
66 lines (52 loc) · 1.37 KB
/
otel_slog_handler.go
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
package bunrouterslog
import (
"context"
"errors"
"log/slog"
"go.opentelemetry.io/otel/attribute"
"go.opentelemetry.io/otel/trace"
)
type handler struct {
inner slog.Handler
}
func NewOtelEventHandler(ctx context.Context, inner slog.Handler) slog.Handler {
return &handler{inner: inner}
}
func (h *handler) Enabled(ctx context.Context, level slog.Level) bool {
return h.inner.Enabled(ctx, level)
}
func (h *handler) Handle(ctx context.Context, r slog.Record) error {
span := trace.SpanFromContext(ctx)
if span != nil && span.IsRecording() {
var err error
attrs := []attribute.KeyValue{}
r.Attrs(func(a slog.Attr) bool {
attrs = append(attrs, attribute.Key(a.Key).String(a.String()))
if a.Key != "error" {
return false
}
nerr, ok := a.Value.Any().(error)
if !ok {
return false
}
err = nerr
return false
})
if r.Level >= slog.LevelError {
if err != nil {
span.RecordError(err, trace.WithAttributes(attrs...))
} else {
span.RecordError(errors.New(r.Message), trace.WithAttributes(attrs...))
}
} else {
span.AddEvent(r.Message, trace.WithAttributes(attrs...))
}
}
return h.inner.Handle(ctx, r)
}
func (h *handler) WithAttrs(attrs []slog.Attr) slog.Handler {
return &handler{inner: h.inner.WithAttrs(attrs)}
}
func (h *handler) WithGroup(name string) slog.Handler {
return &handler{inner: h.inner.WithGroup(name)}
}