From fd130799ca1a29431313d1634b60ec6788f4fbd9 Mon Sep 17 00:00:00 2001 From: Stephen Afam-Osemene Date: Wed, 18 Oct 2023 11:41:12 +0100 Subject: [PATCH] Add option to disable baggage members --- README.md | 2 +- slog_otel.go | 15 +++++++++------ 2 files changed, 10 insertions(+), 7 deletions(-) diff --git a/README.md b/README.md index 8bb6d87..7d53098 100644 --- a/README.md +++ b/README.md @@ -7,7 +7,7 @@ Go package that provides an implementation of `log/slog`'s [Handler interface](https://pkg.go.dev/log/slog#Handler) that ensures a strong correlation between log records and [Open-Telemetry spans](https://opentelemetry.io/docs/concepts/signals/traces/#spans) by... 1. Adding [span and trace IDs](https://opentelemetry.io/docs/concepts/signals/traces/#span-context) to the log record. -2. Adding context [baggage](https://opentelemetry.io/docs/concepts/signals/baggage/) members to the log record. +2. Adding context [baggage](https://opentelemetry.io/docs/concepts/signals/baggage/) members to the log record (can be disabled). 3. Adding log record as [span event](https://opentelemetry.io/docs/concepts/signals/traces/#span-events). 4. Adding log record attributes to the span event. 5. Setting [span status](https://opentelemetry.io/docs/concepts/signals/traces/#span-status) based on slog record level (only if >= slog.LevelError). diff --git a/slog_otel.go b/slog_otel.go index cee37a9..428c206 100644 --- a/slog_otel.go +++ b/slog_otel.go @@ -3,9 +3,8 @@ package slogotel import ( "context" "fmt" - "time" - "log/slog" + "time" "go.opentelemetry.io/otel/attribute" "go.opentelemetry.io/otel/baggage" @@ -25,6 +24,8 @@ import ( type OtelHandler struct { // Next represents the next handler in the chain. Next slog.Handler + // NoBaggage determines whether to add context baggage members to the log record. + NoBaggage bool } // HandlerFn defines the handler used by slog.Handler as return value. @@ -45,10 +46,12 @@ func (h OtelHandler) Handle(ctx context.Context, record slog.Record) error { return h.Next.Handle(ctx, record) } - // Adding context baggage members to log record. - b := baggage.FromContext(ctx) - for _, m := range b.Members() { - record.AddAttrs(slog.String(m.Key(), m.Value())) + if !h.NoBaggage { + // Adding context baggage members to log record. + b := baggage.FromContext(ctx) + for _, m := range b.Members() { + record.AddAttrs(slog.String(m.Key(), m.Value())) + } } span := trace.SpanFromContext(ctx)