Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add option to disable baggage members #6

Merged
merged 1 commit into from
Oct 19, 2023
Merged
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: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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).
Expand Down
15 changes: 9 additions & 6 deletions slog_otel.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,8 @@ package slogotel
import (
"context"
"fmt"
"time"

"log/slog"
"time"

"go.opentelemetry.io/otel/attribute"
"go.opentelemetry.io/otel/baggage"
Expand All @@ -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.
Expand All @@ -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)
Expand Down