Documentation
¶
Overview ¶
Package log wraps log/slog with a context-aware handler that injects W3C trace IDs from ctx so a single request — HTTP, WS envelope, sweeper tick — can be grepped end-to-end by `trace_id`.
Index ¶
- Constants
- func Bg() *slog.Logger
- func Ctx(ctx context.Context) ctxLogger
- func HTTPMiddleware(next http.Handler) http.Handler
- func Init(cfg Config)
- func RequestIDFromContext(ctx context.Context) (string, bool)
- func Warn(ctx context.Context, msg string, args ...any)
- func With(args ...any) *slog.Logger
- func WithRequestID(ctx context.Context, id string) context.Context
- func WithTrace(ctx context.Context, c Carrier) context.Context
- type Carrier
- type Config
- type ContextHandler
- type SpanID
- type TraceID
Constants ¶
const ( AttrTraceID = "trace_id" AttrSpanID = "span_id" AttrRequestID = "request_id" )
AttrTraceID / AttrSpanID are slog attr keys for the W3C IDs, and AttrRequestID for a caller-visible request ID. Stable snake_case so log scrapers can build dashboards on a fixed name.
const HeaderName = "Traceparent"
HeaderName is the canonical HTTP header for W3C traceparent.
Variables ¶
This section is empty.
Functions ¶
func Bg ¶
Bg returns slog.Default for ctx-less startup/init/shutdown sites. Using Bg() in any handler-path code is a bug — it bypasses trace attribution silently.
func Ctx ¶
Ctx returns a ctxLogger so `log.Ctx(ctx).Info(...)` reads cleaner than `slog.Default().InfoContext(ctx, ...)`. ctxLogger is stateless w.r.t. trace IDs — every call re-reads ctx so a child span minted via StartBackgroundTrace is not cached as a stale carrier.
func HTTPMiddleware ¶
HTTPMiddleware adopts a valid inbound `traceparent`, mints a fresh Carrier otherwise, echoes it on the response, and installs it on ctx so downstream `log.Ctx(ctx).Info(...)` gets trace attrs. A malformed header is treated identically to a missing one — never 500 a real request over a logging concern.
func Init ¶
func Init(cfg Config)
Init installs ContextHandler as slog.Default. Calling more than once is a no-op — only one global slog handler exists.
func RequestIDFromContext ¶
RequestIDFromContext returns the ID attached by WithRequestID, or ("", false) when none is present.
func Warn ¶
Warn logs via slog.Default with ctx attached so ContextHandler can inject trace_id/span_id from ctx.
func With ¶
With binds attrs to a child logger that still routes through ContextHandler, so InfoContext etc. still pick up trace_id from ctx.
func WithRequestID ¶
WithRequestID returns ctx annotated with a caller-visible request ID, which ContextHandler emits as request_id next to trace_id. An empty ID is a no-op. HTTPMiddleware never sets one; a service that returns request IDs to its callers attaches them in its own middleware.
Types ¶
type Carrier ¶
Carrier is the in-memory form of a W3C `traceparent` value (`00-{32hex trace_id}-{16hex span_id}-{2hex flags}`). We do not parse `tracestate`. Sampled tracks the low bit of the flags byte; auto-generated carriers default to true.
func NewCarrier ¶
func NewCarrier() Carrier
NewCarrier returns a fresh Carrier with newly-minted trace + span IDs.
func ParseTraceparent ¶
ParseTraceparent parses a W3C traceparent string. Any deviation (wrong length, bad hex, reserved sentinels) yields an error and callers should treat it as "no trace present".
func StartBackgroundTrace ¶
StartBackgroundTrace returns a child ctx carrying a fresh Carrier so any log under it picks up a stable trace_id. Use at the top of every non-HTTP logical-request entrypoint (sweeper tick, WS envelope handler, CLI command).
func TraceFromContext ¶
TraceFromContext returns the Carrier attached by WithTrace, or (zero, false) when none is present.
type Config ¶
type Config struct {
// Format is "json" or "text". Empty auto-detects: text on a TTY,
// JSON otherwise.
Format string
// Level is the minimum slog level. Empty defaults to Info.
Level slog.Level
// AddSource toggles slog's filename:line attribute (~hundreds of
// ns per line — fine in dev, costly in prod).
AddSource bool
// Out is the destination writer. Nil defaults to os.Stderr.
Out io.Writer
}
Config drives Init.
func LoadConfig ¶ added in v0.0.10
LoadConfig reads the logging settings Core and Web share:
OAC_LOG_LEVEL = debug | info | warn | error (default: info) OAC_LOG_FORMAT = auto | json | text (default: auto) OAC_LOG_ADD_SOURCE = 0 | 1 (default: 0)
Unset or empty selects the default. Any other value is an error that names the variable and never echoes the value.
type ContextHandler ¶
type ContextHandler struct {
// contains filtered or unexported fields
}
ContextHandler wraps a slog.Handler and injects trace_id/span_id and any request_id from the record's ctx. Records with no Carrier pass through unchanged so background tasks don't get fake all-zero IDs.
func NewContextHandler ¶
func NewContextHandler(inner slog.Handler) *ContextHandler
type SpanID ¶
type SpanID [8]byte
SpanID is the W3C span-id: 8 random bytes, 16 lowercase hex chars. All-zero is reserved.
func ParseSpanID ¶
ParseSpanID decodes a 16-char lowercase hex string. Rejects all-zero.
type TraceID ¶
type TraceID [16]byte
TraceID is the W3C trace-id: 16 random bytes, rendered as 32 lowercase hex chars. All-zero is reserved and rejected by parsers.
func NewTraceID ¶
func NewTraceID() TraceID
NewTraceID returns a fresh random TraceID. On the vanishingly rare crypto/rand failure the result is the zero ID; the handler then skips trace-attr injection rather than emitting all-zero strings.
func ParseTraceID ¶
ParseTraceID decodes a 32-char lowercase hex string. Rejects all-zero per W3C reserved-sentinel rule.