package logging import ( "context" "log/slog" "go.opentelemetry.io/otel/trace" ) // stampedKey marks a context whose record already carries the ids, so a // traceHandler nested under another one does not stamp them twice. type stampedKey struct{} // traceHandler stamps the trace and span ids of ctx's span on each record. // It must wrap every other handler: none of them reads ctx. type traceHandler struct{ inner slog.Handler } // WithTrace wraps handler so records logged under a valid span carry // trace_id and span_id. func WithTrace(handler slog.Handler) slog.Handler { return traceHandler{inner: handler} } func (h traceHandler) Enabled(ctx context.Context, level slog.Level) bool { return h.inner.Enabled(ctx, level) } func (h traceHandler) Handle(ctx context.Context, record slog.Record) error { if sc := trace.SpanContextFromContext(ctx); sc.IsValid() && ctx.Value(stampedKey{}) == nil { record.AddAttrs( slog.String("trace_id", sc.TraceID().String()), slog.String("span_id", sc.SpanID().String()), ) ctx = context.WithValue(ctx, stampedKey{}, true) } return h.inner.Handle(ctx, record) } func (h traceHandler) WithAttrs(attrs []slog.Attr) slog.Handler { return traceHandler{inner: h.inner.WithAttrs(attrs)} } func (h traceHandler) WithGroup(name string) slog.Handler { return traceHandler{inner: h.inner.WithGroup(name)} }