Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
120 changes: 120 additions & 0 deletions otel/baggage_key_test.go
Original file line number Diff line number Diff line change
@@ -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)
}
}
21 changes: 16 additions & 5 deletions otel/handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 (
Expand All @@ -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).
Expand Down Expand Up @@ -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 {
Expand All @@ -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...)})
}
}

Expand Down
15 changes: 15 additions & 0 deletions otel/handler_benchmark_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import (
"log/slog"
"testing"

"go.opentelemetry.io/otel/baggage"
"go.opentelemetry.io/otel/trace"
)

Expand All @@ -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 {
Expand Down
Loading