Files
galaxy-game/rtmanager/internal/logging/context.go
T
2026-04-28 20:39:18 +02:00

44 lines
1.3 KiB
Go

package logging
import "context"
// requestIDKey is the unexported context key under which the HTTP layer
// stores the request id propagated from the X-Request-Id header.
type requestIDKey struct{}
// WithRequestID returns a child context that carries requestID. An empty
// requestID returns ctx unchanged so callers do not have to branch.
func WithRequestID(ctx context.Context, requestID string) context.Context {
if ctx == nil || requestID == "" {
return ctx
}
return context.WithValue(ctx, requestIDKey{}, requestID)
}
// RequestIDFromContext returns the request id stored on ctx by
// WithRequestID, or an empty string when no value is present.
func RequestIDFromContext(ctx context.Context) string {
if ctx == nil {
return ""
}
value, _ := ctx.Value(requestIDKey{}).(string)
return value
}
// ContextAttrs returns slog key-value pairs that materialise the frozen
// `rtmanager/README.md` §Observability log fields `request_id`,
// `trace_id`, and `span_id` from ctx. Pairs whose value is empty are
// omitted so logs stay tight.
func ContextAttrs(ctx context.Context) []any {
if ctx == nil {
return nil
}
var attrs []any
if requestID := RequestIDFromContext(ctx); requestID != "" {
attrs = append(attrs, "request_id", requestID)
}
attrs = append(attrs, TraceAttrsFromContext(ctx)...)
return attrs
}