context.go47 lines, 1.5 KB
| 1 | package logging |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "log/slog" |
| 6 | "slices" |
| 7 | |
| 8 | "go.opentelemetry.io/otel/trace" |
| 9 | ) |
| 10 | |
| 11 | type attrsKey struct{} |
| 12 | |
| 13 | // With returns a copy of ctx that carries attrs. Loggers made by New add them |
| 14 | // to every line logged with that context, through methods like InfoContext. |
| 15 | func With(ctx context.Context, attrs ...slog.Attr) context.Context { |
| 16 | prev, _ := ctx.Value(attrsKey{}).([]slog.Attr) |
| 17 | return context.WithValue(ctx, attrsKey{}, slices.Concat(prev, attrs)) |
| 18 | } |
| 19 | |
| 20 | // contextHandler adds the attributes stored by With to each record, and then |
| 21 | // passes it on to the real handler. |
| 22 | type contextHandler struct { |
| 23 | slog.Handler |
| 24 | } |
| 25 | |
| 26 | func (h contextHandler) Handle(ctx context.Context, r slog.Record) error { |
| 27 | if attrs, ok := ctx.Value(attrsKey{}).([]slog.Attr); ok { |
| 28 | r.AddAttrs(attrs...) |
| 29 | } |
| 30 | // The trace this line belongs to: search for its ID in Jaeger, or in the |
| 31 | // logs of every service. |
| 32 | if sc := trace.SpanContextFromContext(ctx); sc.IsValid() { |
| 33 | r.AddAttrs(slog.String("trace_id", sc.TraceID().String()), |
| 34 | slog.String("span_id", sc.SpanID().String())) |
| 35 | } |
| 36 | return h.Handler.Handle(ctx, r) |
| 37 | } |
| 38 | |
| 39 | // WithAttrs and WithGroup must wrap their result too. The embedded methods |
| 40 | // would return the bare inner handler, and logger.With would drop our wrapper. |
| 41 | func (h contextHandler) WithAttrs(attrs []slog.Attr) slog.Handler { |
| 42 | return contextHandler{h.Handler.WithAttrs(attrs)} |
| 43 | } |
| 44 | |
| 45 | func (h contextHandler) WithGroup(name string) slog.Handler { |
| 46 | return contextHandler{h.Handler.WithGroup(name)} |
| 47 | } |