feat: include tracing only for the recording spans

This commit is contained in:
Samuel Berthe
2024-04-21 23:05:58 +02:00
parent 87620aa801
commit 0a948b00ea
+11 -10
View File
@@ -168,7 +168,7 @@ func NewWithConfig(logger *slog.Logger, config Config) gin.HandlerFunc {
} }
// otel // otel
baseAttributes = extractTraceSpanID(c, config, baseAttributes) baseAttributes = append(baseAttributes, extractTraceSpanID(c, config.WithTraceID, config.WithSpanID)...)
// request body // request body
requestAttributes = append(requestAttributes, slog.Int("length", br.bytes)) requestAttributes = append(requestAttributes, slog.Int("length", br.bytes))
@@ -283,28 +283,29 @@ func AddCustomAttributes(c *gin.Context, attr slog.Attr) {
} }
} }
func extractTraceSpanID(c *gin.Context, config Config, baseAttributes []slog.Attr) []slog.Attr { func extractTraceSpanID(c *gin.Context, withTraceID bool, withSpanID bool) []slog.Attr {
if !(config.WithTraceID || config.WithSpanID) { if !(withTraceID || withSpanID) {
return baseAttributes return []slog.Attr{}
} }
ctx := c.Request.Context() ctx := c.Request.Context()
span := trace.SpanFromContext(ctx) span := trace.SpanFromContext(ctx)
if !span.IsRecording() { if !span.IsRecording() {
return baseAttributes return []slog.Attr{}
} }
attrs := []slog.Attr{}
spanCtx := span.SpanContext() spanCtx := span.SpanContext()
if config.WithTraceID && spanCtx.HasTraceID() { if withTraceID && spanCtx.HasTraceID() {
traceID := trace.SpanFromContext(ctx).SpanContext().TraceID().String() traceID := trace.SpanFromContext(ctx).SpanContext().TraceID().String()
baseAttributes = append(baseAttributes, slog.String(TraceIDKey, traceID)) attrs = append(attrs, slog.String(TraceIDKey, traceID))
} }
if config.WithSpanID && spanCtx.HasSpanID() { if withSpanID && spanCtx.HasSpanID() {
spanID := spanCtx.SpanID().String() spanID := spanCtx.SpanID().String()
baseAttributes = append(baseAttributes, slog.String(SpanIDKey, spanID)) attrs = append(attrs, slog.String(SpanIDKey, spanID))
} }
return baseAttributes return attrs
} }