Skip to content

Commit

Permalink
Merge pull request #3 from remychantenay/fix-baggage-members-to-log-r…
Browse files Browse the repository at this point in the history
…ecord

Fix issue with baggage members when no recording span
  • Loading branch information
remychantenay authored Sep 13, 2023
2 parents b49b410 + b12ded6 commit 42801fd
Showing 1 changed file with 12 additions and 17 deletions.
29 changes: 12 additions & 17 deletions slog_otel.go
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,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()))
}

span := trace.SpanFromContext(ctx)
if span == nil || !span.IsRecording() {
return h.Next.Handle(ctx, record)
Expand All @@ -65,35 +71,24 @@ func (h OtelHandler) Handle(ctx context.Context, record slog.Record) error {
return true
})

// Setting span status if the log is an error.
// Purposely leaving as Unset (default) otherwise.
if record.Level >= slog.LevelError {
span.SetStatus(codes.Error, record.Message)
}

span.AddEvent("log_record", trace.WithAttributes(eventAttrs...))

// Adding span info to log record.
spanContext := span.SpanContext()
logAttrs := make([]slog.Attr, 0)
if spanContext.HasTraceID() {
traceID := spanContext.TraceID().String()
logAttrs = append(logAttrs, slog.String("trace_id", traceID))
record.AddAttrs(slog.String("trace_id", traceID))
}

if spanContext.HasSpanID() {
spanID := spanContext.SpanID().String()
logAttrs = append(logAttrs, slog.String("span_id", spanID))
}

// Adding context baggage attribute to log record.
b := baggage.FromContext(ctx)
for _, m := range b.Members() {
logAttrs = append(logAttrs, slog.String(m.Key(), m.Value()))
record.AddAttrs(slog.String("span_id", spanID))
}

if len(logAttrs) > 0 {
record.AddAttrs(logAttrs...)
// Setting span status if the log is an error.
// Purposely leaving as Unset (default) otherwise.
if record.Level >= slog.LevelError {
span.SetStatus(codes.Error, record.Message)
}

return h.Next.Handle(ctx, record)
Expand Down

0 comments on commit 42801fd

Please sign in to comment.