-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlogging.go
71 lines (55 loc) · 1.52 KB
/
logging.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
67
68
69
70
71
package main
import (
"context"
"fmt"
"log/slog"
"os"
"go.opentelemetry.io/otel/exporters/stdout/stdoutlog"
"go.opentelemetry.io/otel/log/global"
"go.opentelemetry.io/otel/sdk/log"
"go.opentelemetry.io/otel/sdk/resource"
"go.opentelemetry.io/otel/trace"
)
func setupLogging(_ context.Context, res *resource.Resource) *log.LoggerProvider {
exporter, err := stdoutlog.New()
if err != nil {
panic(err)
}
provider := log.NewLoggerProvider(
log.WithProcessor(log.NewBatchProcessor(exporter)),
log.WithResource(res),
)
global.SetLoggerProvider(provider)
return provider
}
type userID struct{}
func (userID) String() string {
return "user_id"
}
type reqID struct{}
func (reqID) String() string {
return "req_id"
}
type ContextHandler struct {
slog.Handler
ctxKeys []fmt.Stringer
}
// Handle adds contextual attributes to the Record before calling the underlying
// handler
func (h ContextHandler) Handle(ctx context.Context, r slog.Record) error {
if ctx == nil {
return nil
}
span := trace.SpanFromContext(ctx)
r.AddAttrs(slog.String("trace_id", span.SpanContext().TraceID().String()))
r.AddAttrs(slog.String("span_id", span.SpanContext().SpanID().String()))
// required for correlating logs in x-ray to the correct span
r.AddAttrs(slog.String("_X_AMAZN_TRACE_ID", os.Getenv("_X_AMZN_TRACE_ID")))
// adding custom fields from the context to the logs
for _, v := range h.ctxKeys {
if value := ctx.Value(v); value != nil {
r.AddAttrs(slog.Any(v.String(), value))
}
}
return h.Handler.Handle(ctx, r)
}