Documentation
¶
Overview ¶
Package logging is the Go representation of pleme-io's structured-logging convention. It mirrors the Rust `tracing` + `tracing-subscriber` stack and `pleme-actions-shared::log`, so Go services and tools emit logs the same way everywhere — built entirely on the standard library's log/slog.
The mandate, like the Rust side: no ad-hoc fmt.Println logging, no bespoke per-service log formats. Construct one logger with New, thread context through the call graph, and let context-carried fields (correlation ID, tenant) attach to every record automatically.
logger := logging.New(
logging.WithLevelFromEnv("LOG_LEVEL"),
logging.WithFormat("json"),
)
logging.SetDefault(logger)
ctx := logging.WithCorrelationID(context.Background(), "req-123")
ctx = logging.WithTenant(ctx, "acme")
// correlation_id + tenant are injected into the record from ctx:
logging.FromContext(ctx).InfoContext(ctx, "handled request", "status", 200)
The default handler emits JSON to stdout, with the level taken from an option or the LOG_LEVEL environment variable (debug/info/warn/error), defaulting to info. Use WithFormat to switch to the text handler, WithWriter to redirect output, and WithAddSource to annotate records with source locations — the same knobs tracing-subscriber exposes.
Index ¶
- Constants
- func CorrelationIDExtractor(ctx context.Context) []slog.Attr
- func CorrelationIDFromContext(ctx context.Context) (string, bool)
- func Default() *slog.Logger
- func FromConfig(cfg Config, opts ...Option) (*slog.Logger, error)
- func FromContext(ctx context.Context) *slog.Logger
- func LevelVarOf(logger *slog.Logger) *slog.LevelVar
- func New(opts ...Option) *slog.Logger
- func NewContext(ctx context.Context, logger *slog.Logger) context.Context
- func ParseLevel(name string) (slog.Level, error)
- func Pipe(sink slog.Handler, middlewares ...Middleware) slog.Handler
- func SetDefault(logger *slog.Logger)
- func SetLevel(logger *slog.Logger, level slog.Level) bool
- func TenantExtractor(ctx context.Context) []slog.Attr
- func TenantFromContext(ctx context.Context) (string, bool)
- func WithCorrelationID(ctx context.Context, id string) context.Context
- func WithTenant(ctx context.Context, tenant string) context.Context
- type Config
- type ContextHandler
- func (h *ContextHandler) Enabled(ctx context.Context, level slog.Level) bool
- func (h *ContextHandler) Handle(ctx context.Context, record slog.Record) error
- func (h *ContextHandler) LevelVar() *slog.LevelVar
- func (h *ContextHandler) WithAttrs(attrs []slog.Attr) slog.Handler
- func (h *ContextHandler) WithGroup(name string) slog.Handler
- type FieldExtractor
- type Format
- type Middleware
- type Option
- func WithAddSource(add bool) Option
- func WithDiscard() Option
- func WithExtractors(extractors ...FieldExtractor) Option
- func WithFormat(format string) Option
- func WithLevel(level slog.Level) Option
- func WithLevelFromEnv(name string) Option
- func WithLevelVar(v *slog.LevelVar) Option
- func WithMiddleware(mw ...Middleware) Option
- func WithSink(sink SinkFunc) Option
- func WithWriter(w io.Writer) Option
- type SecretString
- type SinkFunc
Constants ¶
const ( // CorrelationIDKey is the record attribute key for the correlation ID // carried in context via [WithCorrelationID]. CorrelationIDKey = "correlation_id" // TenantKey is the record attribute key for the tenant carried in context // via [WithTenant]. TenantKey = "tenant" )
Record attribute keys for the fields injected from context. They are exported so consumers can query, redact, or correlate on the exact same key names the handler writes — the Go analog of tracing's well-known span fields.
const DefaultLevelEnv = "LOG_LEVEL"
DefaultLevelEnv is the environment variable consulted for the log level when WithLevelFromEnv is not given an explicit name. It mirrors the Rust stack's convention of a single well-known level variable.
const Redacted = "[REDACTED]"
Redacted is the placeholder substituted for any value the logger must not render in plaintext. It is the single, stable redaction marker shared by the SecretString LogValuer and the declarative redaction middleware in the logging-go/redact sub-package, so log aggregators see one consistent token.
Variables ¶
This section is empty.
Functions ¶
func CorrelationIDExtractor ¶
CorrelationIDExtractor injects the CorrelationIDKey attribute from a context carrying a correlation ID set via WithCorrelationID. It is one of the two built-in extractors installed by default on every New/FromConfig logger.
func CorrelationIDFromContext ¶
CorrelationIDFromContext returns the correlation ID carried in ctx and whether one was set.
func Default ¶
Default returns the package-level logger. It is never nil. Replace it with SetDefault; reads are lock-free.
func FromConfig ¶
FromConfig builds a *slog.Logger from an already-loaded Config (§3.5). It is the canonical config-consuming constructor: it takes the sub-struct and MUST NOT call shikumi.Load. Extra opts are applied after the config-derived ones, so a caller can layer non-yaml knobs (a SinkFunc for the console, a custom FieldExtractor, redaction Middleware) on top:
log, err := logging.FromConfig(cfg.Logging,
logging.WithSink(console.Sink(theme.Default())),
)
It returns an error only for an invalid Level string; all other fields have safe fallbacks, so the zero Config yields the New default (JSON/stdout/info).
func FromContext ¶
FromContext returns the logger associated with ctx, or the package Default when none is present (including for a nil context). The returned logger is never nil.
Pair it with the *Context log methods so context-carried fields are injected:
logging.FromContext(ctx).InfoContext(ctx, "message", "key", value)
func LevelVarOf ¶
LevelVarOf recovers the live *slog.LevelVar backing a logger built by New, walking through any transparent middleware (those implementing Unwrap). It returns nil when the logger was not built by New (or its level var is hidden behind opaque middleware). The returned var is shared with the logger, so calling Set on it retargets the logger's level live.
func New ¶
New builds a *slog.Logger from the given options.
By default it writes JSON to stdout at info level. The level can be set explicitly with WithLevel or read from the environment with WithLevelFromEnv; the output writer with WithWriter; the format with WithFormat; and source annotation with WithAddSource.
The returned logger's handler is wrapped in a ContextHandler, so any context-carried fields attached via WithCorrelationID / WithTenant are injected into every record emitted through the *Context methods (InfoContext, ErrorContext, …).
func NewContext ¶
NewContext returns a child context carrying logger, so a downstream FromContext returns it instead of the package default. This lets a request boundary install a logger pre-bound with request-scoped attributes (via logger.With(...)) that flows with the context. A nil logger leaves the context unchanged.
func ParseLevel ¶
ParseLevel parses a level name into a slog.Level. Accepted values are "debug", "info", "warn" (alias "warning"), and "error", case-insensitive and surrounding whitespace trimmed — matching the level vocabulary used by the Rust tracing stack. An empty or unrecognised value returns an error and the info level, so callers can fall back deterministically.
func Pipe ¶
func Pipe(sink slog.Handler, middlewares ...Middleware) slog.Handler
Pipe composes middlewares over a base sink handler, returning a single slog.Handler. Middlewares are applied so the first listed is the outermost (runs first); a nil middleware is skipped. With no middlewares it returns the sink unchanged.
h := logging.Pipe(sink, redactMW, injectMW, sampleMW) // record flows: redactMW → injectMW → sampleMW → sink
This is the explicit, testable form of the algebra New applies internally; callers wiring a handler by hand (e.g. for a slog-multi Fanout) use it directly.
func SetDefault ¶
SetDefault atomically installs logger as the package-level default returned by Default and used as the fallback by FromContext. A nil logger is ignored, leaving the current default in place.
func SetLevel ¶
SetLevel retargets the level of a logger built by New live, returning true when it succeeded (the logger exposes a recoverable *slog.LevelVar) and false otherwise. It is the convenience over LevelVarOf for the common case — the hook a shikumi config-reload calls to apply a new level without rebuilding the logger (the zap.AtomicLevel pattern).
logging.SetLevel(log, slog.LevelDebug) // verbose now, live
func TenantExtractor ¶
TenantExtractor injects the TenantKey attribute from a context carrying a tenant set via WithTenant. It is one of the two built-in extractors installed by default on every New/FromConfig logger.
func TenantFromContext ¶
TenantFromContext returns the tenant carried in ctx and whether one was set.
func WithCorrelationID ¶
WithCorrelationID returns a child context carrying the correlation ID. The ID is injected as the CorrelationIDKey attribute on every record logged with the returned context through a ContextHandler (i.e. via the *Context methods such as InfoContext). An empty id leaves the context unchanged.
func WithTenant ¶
WithTenant returns a child context carrying the tenant identifier. The tenant is injected as the TenantKey attribute on every record logged with the returned context through a ContextHandler. An empty tenant leaves the context unchanged.
Types ¶
type Config ¶
type Config struct {
// Level is the minimum level name: debug/info/warn/error (case-insensitive,
// via [ParseLevel]). Empty means info. Applied to a live [*slog.LevelVar],
// so a shikumi reload of this field retargets verbosity via [SetLevel].
Level string `yaml:"level" json:"level"`
// Format selects the sink: json (default) / text / console / discard. An
// unknown value falls back to json. console requires a console [SinkFunc]
// installed via [WithSink] (logging-go/console); without one it degrades to
// text so the zero-dep core stays buildable.
Format string `yaml:"format" json:"format"`
// AddSource toggles file:line source annotation on every record.
AddSource bool `yaml:"addSource" json:"addSource"`
// Output names the destination: "stdout" (default), "stderr", or "discard".
// A file/socket sink is wired by the caller via [WithWriter] rather than a
// path here, keeping the core free of filesystem-open policy. Unknown values
// fall back to stdout.
Output string `yaml:"output" json:"output"`
}
Config is the typed, yaml-tagged knob surface for a logger (Law 3). It is the sub-struct a caller's shikumi-loaded root config embeds:
type Root struct {
Logging logging.Config `yaml:"logging"`
// …
}
and hands to FromConfig. Per §3.5, FromConfig consumes this already-loaded struct and MUST NOT itself call shikumi.Load — config loading happens once, at main, via shikumi.For[Root]; every primitive only consumes its sub-struct.
Precedence (args > env > file) is resolved by shikumi during the load, not here. The zero value is a valid config: it logs JSON to stdout at info level.
type ContextHandler ¶
type ContextHandler struct {
// contains filtered or unexported fields
}
ContextHandler is a slog.Handler decorator that injects context-carried fields — the correlation ID and tenant set via WithCorrelationID and WithTenant — into every record it handles. It is the Go analog of a tracing-subscriber layer that enriches events with span fields.
Records emitted through slog's *Context methods (InfoContext, ErrorContext, …) carry the active context, so the fields attach automatically. Records emitted through the plain methods (Info, Error, …) pass a background context and therefore carry no injected fields.
Injected fields are added at the top level of every record, never nested inside an open slog.Logger.WithGroup group — the location is stable so log aggregators can correlate on it unconditionally.
func NewContextHandler ¶
func NewContextHandler(inner slog.Handler) *ContextHandler
NewContextHandler wraps inner so that context-carried fields are injected into every record. The returned handler delegates level filtering, attribute grouping, and formatting to inner. It uses the built-in extractor registry (correlation_id + tenant); use NewContextHandlerWithExtractors to inject a custom set of [FieldExtractor]s.
func NewContextHandlerWithExtractors ¶
func NewContextHandlerWithExtractors(inner slog.Handler, extractors ...FieldExtractor) *ContextHandler
NewContextHandlerWithExtractors wraps inner with an explicit registry of [FieldExtractor]s run (in order) to produce the injected top-level fields. Passing no extractors falls back to the built-in correlation_id + tenant set, matching NewContextHandler. Pass CorrelationIDExtractor/TenantExtractor explicitly to keep them alongside a custom extractor; omit them to drop them.
func (*ContextHandler) Enabled ¶
Enabled reports whether the wrapped handler emits records at the given level.
func (*ContextHandler) Handle ¶
Handle injects the context-carried correlation ID and tenant (when present) as top-level record attributes, then forwards the record to the wrapped handler.
With no group open, the fields are added directly to the record. With a group open, the injected fields are bound to the pre-group (root) handler and the recorded group/attr operations are replayed on top, so the injected fields stay at the top level while call-site attributes remain inside their group.
func (*ContextHandler) LevelVar ¶
func (h *ContextHandler) LevelVar() *slog.LevelVar
LevelVar returns the live level source the ContextHandler was built with by New, or nil when it was constructed directly. Use it to retarget verbosity at runtime: ch.LevelVar().Set(slog.LevelDebug).
func (*ContextHandler) WithAttrs ¶
func (h *ContextHandler) WithAttrs(attrs []slog.Attr) slog.Handler
WithAttrs returns a new ContextHandler whose wrapped handler carries the given attributes, preserving the context-injection behaviour. Attributes added before any group stay top-level; attributes added after a group is open land inside that group — matching plain slog handler semantics.
func (*ContextHandler) WithGroup ¶
func (h *ContextHandler) WithGroup(name string) slog.Handler
WithGroup returns a new ContextHandler whose wrapped handler opens the named group, preserving the context-injection behaviour. Injected context fields continue to land at the top level, outside the opened group. An empty name is a no-op, per the slog.Handler contract.
type FieldExtractor ¶
FieldExtractor pulls zero or more slog.Attr from a context, to be injected at the top level of every record by a ContextHandler. It is the pluggable generalization of the two originally-hardcoded context fields: correlation_id and tenant are now ordinary built-in extractors (CorrelationIDExtractor, TenantExtractor), and new sources — trace_id/span_id from an OTel span, a request ID, a user ID — opt in by registering another extractor.
An extractor MUST be cheap and allocation-light: it runs on every record that passes the level filter. It MUST NOT mutate the context or block. Returning a nil/empty slice when nothing applies is the expected fast path.
This mirrors the Rust tracing stack, where span fields are likewise a registry of layers enriching every event, not two hardcoded columns.
type Format ¶
type Format string
Format selects the slog handler used to render records.
const ( // FormatJSON renders records with [slog.JSONHandler] — the default, // machine-parseable format used in production. FormatJSON Format = "json" // FormatText renders records with [slog.TextHandler] — a human-readable // key=value format handy for local development. FormatText Format = "text" // FormatConsole renders records through the borealis themed console handler // (level → comp.Glyph, attrs → comp.KV) for dev/CLI output. The themed sink // lives in the gated logging-go/console leaf sub-package (Law 8); selecting // it here without installing a console sink via [WithHandlerFunc] falls back // to the text handler, so the zero-dep core stays buildable offline. FormatConsole Format = "console" // FormatDiscard sends records to [slog.DiscardHandler] (Go 1.24), the // canonical no-op sink for tests and the disabled/unconfigured path. It // drops every record with negligible overhead — the GSDS // default-when-unconfigured handler (OBS-12). FormatDiscard Format = "discard" )
type Middleware ¶
Middleware is a slog.Handler decorator: it wraps an inner handler and returns a new handler that adds one cross-cutting concern (redaction, sampling, field injection, fan-out, …) before delegating. It is the universal composition seam Law 2 mandates — we compose over slog's own Handler interface rather than inventing a bespoke owner type — and matches samber/slog-multi's `Middleware = func(slog.Handler) slog.Handler`, so any middleware from that ecosystem (slog-sampling's Threshold/Uniform, slog-formatter's FormatByKey/PIIFormatter) drops straight into our pipeline.
The canonical pipeline order, innermost-sink-last, is:
redact → inject (ContextHandler) → sample → sink
expressed as a slice of Middleware applied over the format sink. Earlier entries wrap later ones, so the first Middleware is the outermost decorator and runs first on each record.
type Option ¶
type Option func(*config)
Option configures New using the functional-options pattern, matching the house style across the pleme-io Go libraries.
func WithAddSource ¶
WithAddSource toggles source-location annotation. When enabled, each record carries the file and line of the log call (slog's AddSource), mirroring tracing's source spans. Off by default.
func WithDiscard ¶
func WithDiscard() Option
WithDiscard routes output to slog.DiscardHandler, the no-op sink for tests and the disabled path. Equivalent to selecting FormatDiscard. It overrides any format and writer.
func WithExtractors ¶
func WithExtractors(extractors ...FieldExtractor) Option
WithExtractors sets the FieldExtractor registry the ContextHandler runs to inject top-level fields from context. Passing extractors here REPLACES the built-in correlation_id + tenant set, so include CorrelationIDExtractor and TenantExtractor explicitly to keep them. With no call, the built-in set is used. Repeated calls accumulate onto the explicit set.
func WithFormat ¶
WithFormat selects the output format: "json" (default) or "text". Any other value is ignored, leaving the current format in place. The string form is accepted (rather than the Format type) so callers can wire it straight from a config field or flag.
func WithLevel ¶
WithLevel sets the minimum level a record must meet to be emitted. Records below this level are dropped. This takes precedence over any environment variable resolved by WithLevelFromEnv when both are supplied, with the last option applied winning.
func WithLevelFromEnv ¶
WithLevelFromEnv sets the minimum level from the named environment variable, parsed via ParseLevel (debug/info/warn/error, case-insensitive). If name is empty, DefaultLevelEnv ("LOG_LEVEL") is used. If the variable is unset or unparseable, the current level is left unchanged (info by default).
func WithLevelVar ¶
WithLevelVar installs an externally-owned *slog.LevelVar as the logger's level source, enabling live verbosity changes after construction — the zap AtomicLevel pattern, and the mechanism by which a shikumi config reload can retarget verbosity without rebuilding the logger. The caller retains the LevelVar and calls its Set method (or SetLevel on the logger returned by New) to change the level at runtime. A nil var is ignored.
When no LevelVar is supplied, New allocates one internally seeded from the resolved static level, so SetLevel/LevelVarOf always work; pass your own only when you need to share it across several loggers.
func WithMiddleware ¶
func WithMiddleware(mw ...Middleware) Option
WithMiddleware appends Middleware decorators to the handler pipeline. Each is a `func(slog.Handler) slog.Handler`; they are applied in the canonical order redact → inject → sample → sink, with the supplied middlewares wrapping the built-in ContextHandler inject stage (so they see records before context fields are injected — the right place for redaction). Middlewares from samber/slog-multi, slog-sampling, and slog-formatter compose here unchanged. nil middlewares are skipped. Repeated calls accumulate.
func WithSink ¶
WithSink injects a terminal SinkFunc used to build the innermost handler, overriding the format-derived built-in sink. It is how the gated borealis console sink (logging-go/console) is wired in without the core importing it (Law 8): logging-go/console exposes a SinkFunc that callers pass here. A nil sink, or a sink that returns nil, falls back to the format-derived built-in.
func WithWriter ¶
WithWriter directs log output to w instead of stdout. A nil writer is ignored, leaving the default in place.
type SecretString ¶
type SecretString string
SecretString wraps a sensitive string — an Akeyless token, an API key, a password — so that logging it can never leak the plaintext. It implements slog.LogValuer (and fmt.Stringer / fmt.GoStringer) to return Redacted in every rendering path, making plaintext token logging structurally hard rather than relying on every call site to remember to redact.
This is the zero-dep, opt-in companion to the declarative key-based redaction in the logging-go/redact sub-package: SecretString protects a value wherever it travels (you log the typed value), while redact protects by attribute key (you redact at the sink regardless of how the value was typed). Use both — type the value AND redact the key.
tok := logging.SecretString(rawToken) logging.FromContext(ctx).InfoContext(ctx, "authenticated", "token", tok) // → ...,"token":"[REDACTED]" (never the plaintext)
The underlying plaintext is still reachable for legitimate use via [Reveal]; only the logging/stringer paths are redacted.
func (SecretString) GoString ¶
func (s SecretString) GoString() string
GoString implements fmt.GoStringer, so even %#v formatting redacts.
func (SecretString) LogValue ¶
func (s SecretString) LogValue() slog.Value
LogValue implements slog.LogValuer, yielding the Redacted marker so the secret is never serialized by any slog handler.
func (SecretString) Reveal ¶
func (s SecretString) Reveal() string
Reveal returns the underlying plaintext for legitimate non-logging use (e.g. sending the token to the API it authenticates). It is the deliberate, named escape hatch — grep-auditable — so revealing a secret is always an explicit act, never an accident of formatting.
func (SecretString) String ¶
func (s SecretString) String() string
String implements fmt.Stringer, so a SecretString printed with %s / %v — the common accidental-leak path — also shows Redacted.
type SinkFunc ¶
SinkFunc builds the terminal (innermost) slog.Handler from the resolved writer and handler options. It is the seam through which a gated sink — e.g. the borealis console handler in logging-go/console — is injected into the core's pipeline without the core importing it (Law 8). When it returns nil the core falls back to its built-in sink for the configured format.