Enhance Logging: Include TraceID and SpanID only for Recording Spans (#20)
Logging non-recording spans is uninformative for troubleshooting and absent in tracing platforms like Jaeger. Co-authored-by: Samuel Berthe <dev@samuel-berthe.fr>
This commit is contained in:
+28
-10
@@ -1,12 +1,11 @@
|
|||||||
package sloggin
|
package sloggin
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"log/slog"
|
||||||
"net/http"
|
"net/http"
|
||||||
"strings"
|
"strings"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"log/slog"
|
|
||||||
|
|
||||||
"github.com/gin-gonic/gin"
|
"github.com/gin-gonic/gin"
|
||||||
"github.com/google/uuid"
|
"github.com/google/uuid"
|
||||||
"go.opentelemetry.io/otel/trace"
|
"go.opentelemetry.io/otel/trace"
|
||||||
@@ -169,14 +168,7 @@ func NewWithConfig(logger *slog.Logger, config Config) gin.HandlerFunc {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// otel
|
// otel
|
||||||
if config.WithTraceID {
|
baseAttributes = extractTraceSpanID(c, config, baseAttributes)
|
||||||
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))
|
|
||||||
}
|
|
||||||
|
|
||||||
// request body
|
// request body
|
||||||
requestAttributes = append(requestAttributes, slog.Int("length", br.bytes))
|
requestAttributes = append(requestAttributes, slog.Int("length", br.bytes))
|
||||||
@@ -290,3 +282,29 @@ func AddCustomAttributes(c *gin.Context, attr slog.Attr) {
|
|||||||
c.Set(customAttributesCtxKey, append(attrs, attr))
|
c.Set(customAttributesCtxKey, append(attrs, attr))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func extractTraceSpanID(c *gin.Context, config Config, baseAttributes []slog.Attr) []slog.Attr {
|
||||||
|
if !(config.WithTraceID || config.WithSpanID) {
|
||||||
|
return baseAttributes
|
||||||
|
}
|
||||||
|
|
||||||
|
ctx := c.Request.Context()
|
||||||
|
span := trace.SpanFromContext(ctx)
|
||||||
|
if !span.IsRecording() {
|
||||||
|
return baseAttributes
|
||||||
|
}
|
||||||
|
|
||||||
|
spanCtx := span.SpanContext()
|
||||||
|
|
||||||
|
if config.WithTraceID && spanCtx.HasTraceID() {
|
||||||
|
traceID := trace.SpanFromContext(ctx).SpanContext().TraceID().String()
|
||||||
|
baseAttributes = append(baseAttributes, slog.String(TraceIDKey, traceID))
|
||||||
|
}
|
||||||
|
|
||||||
|
if config.WithSpanID && spanCtx.HasSpanID() {
|
||||||
|
spanID := spanCtx.SpanID().String()
|
||||||
|
baseAttributes = append(baseAttributes, slog.String(SpanIDKey, spanID))
|
||||||
|
}
|
||||||
|
|
||||||
|
return baseAttributes
|
||||||
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user