Skip to content

Commit

Permalink
feat: include tracing only for the recording spans
Browse files Browse the repository at this point in the history
  • Loading branch information
samber committed Apr 21, 2024
1 parent f4201b0 commit 2a8bf71
Showing 1 changed file with 28 additions and 8 deletions.
36 changes: 28 additions & 8 deletions middleware.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package slogecho

import (
"context"
"errors"
"net/http"
"strings"
Expand Down Expand Up @@ -178,14 +179,7 @@ func NewWithConfig(logger *slog.Logger, config Config) echo.MiddlewareFunc {
}

// otel
if config.WithTraceID {
traceID := trace.SpanFromContext(c.Request().Context()).SpanContext().TraceID().String()
baseAttributes = append(baseAttributes, slog.String(TraceIDKey, traceID))
}
if config.WithSpanID {
spanID := trace.SpanFromContext(c.Request().Context()).SpanContext().SpanID().String()
baseAttributes = append(baseAttributes, slog.String(SpanIDKey, spanID))
}
baseAttributes = append(baseAttributes, extractTraceSpanID(c.Request().Context(), config.WithTraceID, config.WithSpanID)...)

// request body
requestAttributes = append(requestAttributes, slog.Int("length", br.bytes))
Expand Down Expand Up @@ -304,3 +298,29 @@ func AddCustomAttributes(c echo.Context, attr slog.Attr) {
c.Set(customAttributesCtxKey, append(attrs, attr))
}
}

func extractTraceSpanID(ctx context.Context, withTraceID bool, withSpanID bool) []slog.Attr {
if !(withTraceID || withSpanID) {
return []slog.Attr{}
}

span := trace.SpanFromContext(ctx)
if !span.IsRecording() {
return []slog.Attr{}
}

attrs := []slog.Attr{}
spanCtx := span.SpanContext()

if withTraceID && spanCtx.HasTraceID() {
traceID := trace.SpanFromContext(ctx).SpanContext().TraceID().String()
attrs = append(attrs, slog.String(TraceIDKey, traceID))
}

if withSpanID && spanCtx.HasSpanID() {
spanID := spanCtx.SpanID().String()
attrs = append(attrs, slog.String(SpanIDKey, spanID))
}

return attrs
}

0 comments on commit 2a8bf71

Please sign in to comment.