From 38c91e9315b24de4bf8b230bf541c67ff6a6bc9f Mon Sep 17 00:00:00 2001 From: Josue Giron Date: Sat, 21 Nov 2026 20:27:11 +0000 Subject: [PATCH] fix(otel): log baggage members under a baggage group Baggage members were added as top-level record attributes, so a member key could duplicate a record key such as msg or level. Log them under the new BaggageKey group instead. Co-Authored-By: Claude Opus 5.5 --- README.md | 2 + otel/baggage_key_test.go | 120 +++++++++++++++++++++++++++++++++ otel/handler.go | 21 ++++-- otel/handler_benchmark_test.go | 15 +++++ 4 files changed, 153 insertions(+), 5 deletions(-) create mode 100644 otel/baggage_key_test.go diff --git a/README.md b/README.md index f4be740..a83bd02 100644 --- a/README.md +++ b/README.md @@ -145,6 +145,8 @@ sanitized. Baggage can contain tenant identifiers, tokens, or other sensitive values; use `WithBaggageAllowList`, `WithBaggageDenyList`, or `WithBaggageFilter` to keep log output intentional. +From `log/otel` v1.9.0 baggage members are logged under a `baggage` group (`"baggage":{"request_id":"r1"}` in JSON, `baggage.request_id` on span events), so a member key chosen by the caller, such as `msg` or `level`, cannot replace a record key. Earlier versions added them as top-level attributes. + ## Verification ```bash diff --git a/otel/baggage_key_test.go b/otel/baggage_key_test.go new file mode 100644 index 0000000..0e966e9 --- /dev/null +++ b/otel/baggage_key_test.go @@ -0,0 +1,120 @@ +package otel + +import ( + "bytes" + "context" + "encoding/json" + "log/slog" + "strings" + "testing" + + "go.opentelemetry.io/otel/baggage" + "go.opentelemetry.io/otel/trace" +) + +func TestBaggageCannotOverrideRecordKeys(t *testing.T) { + var out bytes.Buffer + logger := slog.New(New(slog.NewJSONHandler(&out, nil), WithNoBaggage(false))) + bag, err := baggage.Parse("level=INFO,msg=user%20logged%20out,time=0,source=x,trace_id=00000000000000000000000000000001,span_id=0000000000000001,order=forged,request_id=r1") + if err != nil { + t.Fatalf("baggage.Parse() error = %v", err) + } + + logger.ErrorContext(baggage.ContextWithBaggage(context.Background(), bag), "payment fraud detected", "order", "o-1") + + var line map[string]any + if err := json.Unmarshal(out.Bytes(), &line); err != nil { + t.Fatalf("json.Unmarshal(%s) error = %v", out.String(), err) + } + want := map[string]any{"level": "ERROR", "msg": "payment fraud detected", "order": "o-1"} + for key, value := range want { + if line[key] != value { + t.Errorf("%s = %v, want %v (line %s)", key, line[key], value, out.String()) + } + } + for _, key := range []string{"trace_id", "span_id", "source"} { + if _, ok := line[key]; ok { + t.Errorf("baggage set top-level %q: %s", key, out.String()) + } + } + if line["time"] == "0" { + t.Errorf("baggage replaced time: %s", out.String()) + } + bagGroup, ok := line[BaggageKey].(map[string]any) + if !ok { + t.Fatalf("baggage group = %v, want members under %q (line %s)", line[BaggageKey], BaggageKey, out.String()) + } + for _, key := range []string{"level", "msg", "time", "source", "trace_id", "span_id", "order", "request_id"} { + if _, ok := bagGroup[key]; !ok { + t.Errorf("baggage member %q missing from the group (line %s)", key, out.String()) + } + } +} + +func TestBaggageDoesNotReplaceSpanIDs(t *testing.T) { + var out bytes.Buffer + logger := slog.New(New(slog.NewJSONHandler(&out, nil), WithNoBaggage(false))) + spanContext := trace.NewSpanContext(trace.SpanContextConfig{ + TraceID: trace.TraceID{0xaa}, + SpanID: trace.SpanID{0xbb}, + }) + ctx := trace.ContextWithSpan(context.Background(), &recordingSpan{spanContext: spanContext}) + bag, err := baggage.Parse("trace_id=00000000000000000000000000000001,span_id=0000000000000001") + if err != nil { + t.Fatalf("baggage.Parse() error = %v", err) + } + + logger.InfoContext(baggage.ContextWithBaggage(ctx, bag), "x") + + // Before the fix the baggage IDs were top-level keys too; the decoder keeps + // the last duplicate, so check the raw line. + for _, key := range []string{TraceIDKey, SpanIDKey} { + if got := strings.Count(out.String(), `"`+key+`"`); got != 2 { + t.Errorf("%s keys = %d, want 2 (record and baggage group): %s", key, got, out.String()) + } + } + if !strings.Contains(out.String(), `"`+BaggageKey+`":{`) { + t.Errorf("no %q group: %s", BaggageKey, out.String()) + } + var line map[string]any + if err := json.Unmarshal(out.Bytes(), &line); err != nil { + t.Fatalf("json.Unmarshal(%s) error = %v", out.String(), err) + } + if line[TraceIDKey] != spanContext.TraceID().String() || line[SpanIDKey] != spanContext.SpanID().String() { + t.Fatalf("trace/span IDs = %v/%v, want the span's (line %s)", line[TraceIDKey], line[SpanIDKey], out.String()) + } +} + +func TestBaggageGroupOmittedWhenFilterDropsAllMembers(t *testing.T) { + var out bytes.Buffer + logger := slog.New(New(slog.NewJSONHandler(&out, nil), WithNoBaggage(false), WithBaggageAllowList("tenant"))) + bag, err := baggage.Parse("token=secret") + if err != nil { + t.Fatalf("baggage.Parse() error = %v", err) + } + + logger.InfoContext(baggage.ContextWithBaggage(context.Background(), bag), "x") + + if strings.Contains(out.String(), `"`+BaggageKey+`"`) { + t.Fatalf("expected no baggage group, got %s", out.String()) + } +} + +func TestSpanEventCarriesBaggageUnderGroupKey(t *testing.T) { + span := &recordingSpan{} + ctx := trace.ContextWithSpan(context.Background(), span) + logger := slog.New(New(slog.NewJSONHandler(&bytes.Buffer{}, nil), WithNoBaggage(false))) + bag, err := baggage.Parse("msg=forged,request_id=r1") + if err != nil { + t.Fatalf("baggage.Parse() error = %v", err) + } + + logger.InfoContext(baggage.ContextWithBaggage(ctx, bag), "real") + + if got := eventAttr(t, span, BaggageKey+".request_id").AsString(); got != "r1" { + t.Errorf("baggage.request_id = %q, want r1", got) + } + if got := eventAttr(t, span, "msg").AsString(); got != "real" { + t.Errorf("msg = %q, want real", got) + } +} diff --git a/otel/handler.go b/otel/handler.go index 875b2b4..da060e4 100644 --- a/otel/handler.go +++ b/otel/handler.go @@ -38,6 +38,11 @@ const ( // SpanEventKey is the prefix key used by the Otel handler // to inject the log record in the recording span, as a span event. SpanEventKey = "log" + // BaggageKey is the group under which the Otel handler logs baggage + // members, so a member key cannot replace a record key such as msg or + // level. It is added after the record's attributes; an application + // attribute with the same key would be written twice. + BaggageKey = "baggage" ) const ( @@ -63,7 +68,8 @@ const ( // by: // // 1. Adding otel span and trace IDs to the log record. -// 2. Adding otel context baggage members to the log record. +// 2. Adding otel context baggage members to the log record, under the +// BaggageKey group (e.g. "baggage":{"request_id":"r1"} in JSON). // 3. Setting slog record as otel span event. // 4. Adding slog record attributes to the otel span event. // 5. Setting span status based on slog record level (only if >= slog.LevelError). @@ -176,9 +182,11 @@ func (h OtelHandler) Handle(ctx context.Context, record slog.Record) error { return h.Next.Handle(ctx, record) } if !h.NoBaggage { - // Adding context baggage members to log record. - b := baggage.FromContext(ctx) - for _, m := range b.Members() { + // Adding context baggage members to log record, under their own group: + // member keys come from the caller and must not replace record keys. + bag := baggage.FromContext(ctx).Members() + members := make([]slog.Attr, 0, len(bag)) + for _, m := range bag { key := m.Key() value := m.Value() if h.BaggageFilter != nil { @@ -188,7 +196,10 @@ func (h OtelHandler) Handle(ctx context.Context, record slog.Record) error { } value = filteredValue } - record.AddAttrs(slog.String(key, value)) + members = append(members, slog.String(key, value)) + } + if len(members) > 0 { + record.AddAttrs(slog.Attr{Key: BaggageKey, Value: slog.GroupValue(members...)}) } } diff --git a/otel/handler_benchmark_test.go b/otel/handler_benchmark_test.go index 66beed0..efa9c2e 100644 --- a/otel/handler_benchmark_test.go +++ b/otel/handler_benchmark_test.go @@ -6,6 +6,7 @@ import ( "log/slog" "testing" + "go.opentelemetry.io/otel/baggage" "go.opentelemetry.io/otel/trace" ) @@ -31,6 +32,20 @@ func BenchmarkHandleSpanEvent(b *testing.B) { } } +// BenchmarkHandleBaggage measures a record written with baggage logging on. +func BenchmarkHandleBaggage(b *testing.B) { + logger := slog.New(New(slog.NewJSONHandler(io.Discard, nil), WithNoBaggage(false))) + bag, err := baggage.Parse("request_id=r-123,tenant=acme") + if err != nil { + b.Fatalf("baggage.Parse() error = %v", err) + } + ctx := baggage.ContextWithBaggage(context.Background(), bag) + b.ReportAllocs() + for b.Loop() { + logger.InfoContext(ctx, "order created", "order_id", 42) + } +} + // discardSpan is a recording span that drops events, so the benchmark measures // the handler and not the recorder. type discardSpan struct {