log

package
v0.0.6 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 3, 2026 License: MIT Imports: 10 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Direct slog.{Info,Warn,Error,Debug,Default} use outside this package is blocked by .golangci.yml forbidigo so the ctx-first signatures here are how trace_id auto-injection stays enforceable.

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

View Source
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.

View Source
const HeaderName = "Traceparent"

HeaderName is the canonical HTTP header for W3C traceparent.

Variables

This section is empty.

Functions

func Bg

func Bg() *slog.Logger

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

func Ctx(ctx context.Context) ctxLogger

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 Debug

func Debug(ctx context.Context, msg string, args ...any)

func Discard

func Discard() *slog.Logger

Discard returns a *slog.Logger that drops every record. Wrapped in ContextHandler so tests behave identically to production.

func Error

func Error(ctx context.Context, msg string, args ...any)

func HTTPMiddleware

func HTTPMiddleware(next http.Handler) http.Handler

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 Info

func Info(ctx context.Context, msg string, args ...any)

Info logs via slog.Default with ctx attached so ContextHandler can inject trace_id/span_id from ctx.

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

func RequestIDFromContext(ctx context.Context) (string, bool)

RequestIDFromContext returns the ID attached by WithRequestID, or ("", false) when none is present.

func Warn

func Warn(ctx context.Context, msg string, args ...any)

func With

func With(args ...any) *slog.Logger

With binds attrs to a child logger that still routes through ContextHandler, so InfoContext etc. still pick up trace_id from ctx.

func WithRequestID

func WithRequestID(ctx context.Context, id string) context.Context

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.

func WithTrace

func WithTrace(ctx context.Context, c Carrier) context.Context

WithTrace returns ctx annotated with c. A zero-trace Carrier is a no-op so callers don't need a separate nil-check.

Types

type Carrier

type Carrier struct {
	Trace   TraceID
	Span    SpanID
	Sampled bool
}

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 ChildSpan

func ChildSpan(parent context.Context) (context.Context, Carrier)

ChildSpan returns a ctx with the parent's trace_id and a fresh span_id. If the parent has no carrier, behaves like StartBackgroundTrace so callers don't have to branch on presence.

func NewCarrier

func NewCarrier() Carrier

NewCarrier returns a fresh Carrier with newly-minted trace + span IDs.

func ParseTraceparent

func ParseTraceparent(s string) (Carrier, error)

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

func StartBackgroundTrace(parent context.Context, op string) (context.Context, Carrier)

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). For a sub-step that should keep the trace, use ChildSpan instead.

func TraceFromContext

func TraceFromContext(ctx context.Context) (Carrier, bool)

TraceFromContext returns the Carrier attached by WithTrace, or (zero, false) when none is present.

func (Carrier) ChildSpan

func (c Carrier) ChildSpan() Carrier

ChildSpan returns a Carrier sharing this Trace but with a fresh Span.

func (Carrier) String

func (c Carrier) String() string

String formats the Carrier as a W3C traceparent. Returns "" for a zero-trace Carrier so callers can use it as a presence check.

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 ConfigFromEnv

func ConfigFromEnv() Config

ConfigFromEnv reads:

OAC_LOG_FORMAT     = json | text  (default: auto)
OAC_LOG_LEVEL      = debug | info | warn | error  (default: info)
OAC_LOG_ADD_SOURCE = 0 | 1  (default: 0)

Unknown values fall back to defaults — Init runs before most error-handling exists, so "boot anyway" beats "panic on typo".

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

func (*ContextHandler) Enabled

func (h *ContextHandler) Enabled(ctx context.Context, level slog.Level) bool

func (*ContextHandler) Handle

func (h *ContextHandler) Handle(ctx context.Context, r slog.Record) error

func (*ContextHandler) WithAttrs

func (h *ContextHandler) WithAttrs(attrs []slog.Attr) slog.Handler

WithAttrs / WithGroup MUST re-wrap so slog.Default().With(...) does not unwrap us and silently lose trace_id injection.

func (*ContextHandler) WithGroup

func (h *ContextHandler) WithGroup(name string) slog.Handler

type SpanID

type SpanID [8]byte

SpanID is the W3C span-id: 8 random bytes, 16 lowercase hex chars. All-zero is reserved.

func NewSpanID

func NewSpanID() SpanID

func ParseSpanID

func ParseSpanID(s string) (SpanID, error)

ParseSpanID decodes a 16-char lowercase hex string. Rejects all-zero.

func (SpanID) IsZero

func (s SpanID) IsZero() bool

func (SpanID) String

func (s SpanID) String() string

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

func ParseTraceID(s string) (TraceID, error)

ParseTraceID decodes a 32-char lowercase hex string. Rejects all-zero per W3C reserved-sentinel rule.

func (TraceID) IsZero

func (t TraceID) IsZero() bool

func (TraceID) String

func (t TraceID) String() string

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL