-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlogger.go
53 lines (47 loc) · 1.54 KB
/
logger.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
package telemetrylib
import (
"context"
"go.opentelemetry.io/otel/trace"
"log/slog"
"os"
)
func InitLogger() {
InitLoggerWithOptions(&slog.HandlerOptions{
Level: slog.LevelInfo,
})
}
func InitLoggerWithOptions(options *slog.HandlerOptions) {
jsonHandler := slog.NewJSONHandler(os.Stdout, options)
// Add span context attributes when Context is passed to logging calls.
instrumentedHandler := handlerWithSpanContext(jsonHandler)
// Set this handler as the global slog handler.
slog.SetDefault(slog.New(instrumentedHandler))
}
func handlerWithSpanContext(handler slog.Handler) *spanContextLogHandler {
return &spanContextLogHandler{Handler: handler}
}
// spanContextLogHandler is an slog.Handler which adds attributes from the
// span context.
type spanContextLogHandler struct {
slog.Handler
}
// Handle overrides slog.Handler's Handle method. This adds attributes from the
// span context to the slog.Record.
func (t *spanContextLogHandler) Handle(ctx context.Context, record slog.Record) error {
// Get the SpanContext from the golang Context.
spanContext := trace.SpanContextFromContext(ctx)
if spanContext.IsValid() {
// Add trace context attributes following OpenTelemetry structured log format described
// in https://opentelemetry.io/docs/concepts/signals/traces/
record.AddAttrs(
slog.Any("trace_id", spanContext.TraceID()),
)
record.AddAttrs(
slog.Any("span_id", spanContext.SpanID()),
)
record.AddAttrs(
slog.Bool("trace_sampled", spanContext.TraceFlags().IsSampled()),
)
}
return t.Handler.Handle(ctx, record)
}