logging
v0.3.0
Documentation
pkg.go.dev ↗Package logging provides a slog-backed implementation of github.com/tetratelabs/telemetry optimized for OpenTelemetry, with a key guarantee: metrics are always emitted even when the log level is silenced.
The core guarantee
When you silence Info logs in production to reduce noise, paired metrics still fire. This is because [RecordContext] is called before the level check:
logger.SetLevel(telemetry.LevelError) // Info logs suppressed
logger.Metric(myMetric).Info("reserve success") // log silent, metric still increments
This decouples operational verbosity from alerting signal, the right tradeoff for high-traffic services.
Quick start
// Wire once in main (or TestMain):
sink := log.NewOTelSink(meterProvider, "myservice")
telemetry.SetGlobalMetricSink(sink)
scope.UseLogger(log.New(slog.Default()))
// Declare metrics in library code (no impl dep):
var errs telemetry.Metric
func init() {
telemetry.ToGlobalMetricSink(func(ms telemetry.MetricSink) {
errs = ms.NewSum("myservice_errors_total", "Errors by cluster")
})
}
// One call: log line + metric increment + OTel trace correlation:
logger.Context(ctx).Metric(errs).Error("reserve failed", err, "cluster", cluster)
// → slog: level=ERROR msg="reserve failed" trace_id=abc span_id=def cluster=openai err=...
// → OTel: myservice_errors_total{cluster="openai"} += 1
OTel trace correlation
When a context with an active OTel span is attached via [Logger.Context], trace_id and span_id are automatically injected into every log line. No manual extraction needed.
Cross-cutting attributes (customer_id, environment, service_name, …)
Use SetAttrs or NewAttrs to stamp shared dimensions into a context once. Every downstream logger.Context(ctx) call and metric.RecordContext(ctx, …) call picks them up automatically — no per-call repetition:
// In middleware, after validating the request:
ctx = logging.SetAttrs(ctx,
"customer_id", claims.CustomerID,
"environment", env,
"service_name", "valet",
"product", claims.Product,
)
// In library code — zero knowledge of the dimensions above:
logger.Context(ctx).Metric(requests).Info("request handled")
// → log: msg="request handled" customer_id=acme environment=prod service_name=valet …
// → metric: requests_total{customer_id="acme",environment="prod",service_name="valet"} += 1
Sinks
NewOTelSink: production sink backed by a real OTel go.opentelemetry.io/otel/sdk/metric.MeterProvider. Call OTelSink.Shutdown on exit to flush pending metrics.
NewMemSink: in-memory sink for unit tests. Inspect recorded values with MemSink.Snapshot.
Package log provides a slog-backed implementation of tetratelabs/telemetry.Logger optimized for OpenTelemetry: metrics flow through an OTel MeterProvider, and every log line automatically carries the OTel trace_id and span_id from context when a span is active, making logs and traces trivially correlatable.
Quick start
// Wire once in main:
sink := log.NewOTelSink(meterProvider, "zia")
telemetry.SetGlobalMetricSink(sink)
scope.UseLogger(log.New(slog.Default()))
// In library code:
logger.Metric(errMetric).Error("reserve failed", err, "cluster", cluster)
// → slog: level=ERROR msg="reserve failed" trace_id=abc span_id=def cluster=openai err=...
// → OTel metric: zia_reserve_errors_total{cluster="openai"} += 1
Constants
LevelDebug (6 declarations)
const ( LevelDebug = slog.Level(-4) // DEBUG LevelInfo = slog.Level(0) // INFO LevelNotice = slog.Level(2) // NOTICE (normal but significant) LevelWarning = slog.Level(4) // WARNING (might cause problems) LevelError = slog.Level(8) // ERROR (likely to cause problems) LevelEmergency = slog.Level(12) // EMERGENCY (system is unusable) )
GCP-compatible severity levels as slog.Level constants. These map 1:1 to Cloud Logging severity and fit into slog's int space. https://cloud.google.com/logging/docs/reference/v2/rest/v2/LogEntry#LogSeverity
Functions
GetAttrs
func GetAttrs(ctx context.Context) []any
GetAttrs returns the key-value pairs stored in ctx by SetAttrs or NewAttrs. Returns nil if none are present. The slice is in the same interleaved key, value, key, value order used by SetAttrs.
GetLogAttrs
func GetLogAttrs(ctx context.Context) []any
GetLogAttrs returns the log-only key-value pairs stored in ctx by SetLogAttrs. Returns nil if none are present. The slice is in the interleaved key, value, key, value order used by SetLogAttrs.
Each entry is a string; the result is exposed as []any to match the shape used by GetAttrs so callers can pass it to slog.Attr-style helpers without an extra conversion.
LevelNames
func LevelNames() []string
LevelNames returns a copy of all supported log level names in ascending order.
LevelSlogValue
func LevelSlogValue(l slog.Level) slog.Value
LevelSlogValue returns the pre-allocated slog.Value string for l. Unknown levels return "UNKNOWN".
LevelString
func LevelString(l slog.Level) string
LevelString returns the canonical string name for l. Unlike l.String(), this always returns one of the six GCP severity names (or "UNKNOWN" for values not in the set).
LookupLevel
func LookupLevel(name string) (slog.Level, error)
LookupLevel resolves a level name to a slog.Level. Matching is case-insensitive and leading/trailing whitespace is trimmed. The empty string resolves to LevelInfo. Aliases: WARN -> LevelWarning, ERR/FATAL -> LevelError.
New
func New(sl *slog.Logger) telemetry.Logger
New returns a telemetry.Logger backed by the given *slog.Logger. When a context with an active OTel span is attached via .Context(ctx), trace_id and span_id are automatically added to every log line.
SetAttrs
func SetAttrs(ctx context.Context, keyValuePairs ...string) context.Context
SetAttrs is a convenience one-liner for when you have all key-value pairs ready. It is equivalent to NewAttrs(ctx).Set(k1, v1).Set(k2, v2)...Into(ctx).
ctx = logging.SetAttrs(ctx,
"customer_id", claims.CustomerID,
"environment", env,
"service_name", "valet",
)
SetLevel
func SetLevel(logger *slog.Logger, level slog.Level) *slog.Logger
SetLevel adjusts the level on a logger whose handler implements LevelableHandler. Panics if the handler does not support runtime level changes; use NewLevelHandler when building the logger to guarantee this.
SetLogAttrs
func SetLogAttrs(ctx context.Context, keyValuePairs ...string) context.Context
SetLogAttrs attaches key-value pairs to ctx that flow into log records only. The pairs are NEVER attached to counters, histograms, or gauges.
Multiple calls append; later calls do not replace earlier ones.
ctx = logging.SetLogAttrs(ctx,
"request_id", reqID,
"user_id", userID,
)
keyValuePairs must contain an even number of strings. Odd entries are silently dropped to mirror SetAttrs' tolerant behavior.
TestLogger
func TestLogger(tb testing.TB) *slog.Logger
TestLogger returns a *slog.Logger for use in tests.
It logs everything down to the lowest possible level (all Debug and below), writes via tb.Log so output is tied to the test, visible only on failure or when -v is passed, never mixed into stdout.
Source locations are included so failing test output shows exactly which log call fired.
TestSomething
func TestSomething(t *testing.T) {
logger := log.TestLogger(t)
scope.UseLogger(log.New(logger))
// ... exercise code ...
}
Types
Attrs
type Attrs struct {
// contains filtered or unexported fields
}
Attrs holds a set of key-value pairs that flow through context into both log lines and metric attributes automatically.
Attrs is the BOUNDED scope: use it for low-cardinality enums (customer ID, environment, service name, region) that are safe as metric labels. For UNBOUNDED values like request_id, user_id, raw IP, or anything else with a huge value space, use SetLogAttrs (in logattrs.go) instead. The log-only scope lets request_id decorate log records without exploding counter cardinality.
Wire once at the edge of your service (middleware, gRPC interceptor, handler constructor) and every logger.Context(ctx) call downstream carries the same dimensions without any per-call boilerplate:
// Bounded: safe on metric labels.
ctx = logging.NewAttrs(ctx).
Set("customer_id", claims.CustomerID).
Set("environment", env).
Set("service_name", "valet").
Set("product", claims.Product).
Into(ctx)
// Unbounded: logs only, never metric labels.
ctx = logging.SetLogAttrs(ctx,
"request_id", reqID,
"user_id", claims.UserID,
)
// In library code, no knowledge of the dimensions above:
logger.Context(ctx).Metric(requests).Info("request handled")
// log: msg="request handled" customer_id=acme environment=prod
// service_name=valet product=tare request_id=abc user_id=u-42
// trace_id=...
// metric: requests_total{customer_id="acme",environment="prod",
// service_name="valet",product="tare"} += 1
// (no request_id or user_id on the counter)
NewAttrs
func NewAttrs(ctx context.Context) *Attrs
NewAttrs starts building an Attrs set rooted at ctx. Call Set for each dimension, then Into to stamp them into a new context.
Attrs.Into
func (a *Attrs) Into(ctx context.Context) context.Context
Into stamps all accumulated key-value pairs into the context and returns it. The returned context can be passed to logger.Context(ctx) or metric.RecordContext(ctx, ...) directly; both pick up the pairs automatically.
Into uses telemetry.KeyValuesToContext, which appends to any pairs already present in the context, so it is safe to call multiple times as request attributes are resolved (e.g. once for static service attrs, once for per-request attrs from JWT claims).
Attrs.Set
func (a *Attrs) Set(key, value string) *Attrs
Set adds a key-value pair. Both key and value must be strings. Returns the receiver for chaining.
HTTPLevelHandler
type HTTPLevelHandler struct {
// contains filtered or unexported fields
}
HTTPLevelHandler is an http.Handler that exposes a GET/PUT endpoint for reading and changing the log level at runtime without a restart.
Register it on your admin/pprof mux:
mux.Handle("/log/level", logging.NewHTTPLevelHandler(logger))
GET /log/level -> {"level":"INFO","available_levels":["DEBUG",...]} PUT /log/level <- {"level":"DEBUG"}
-> {"level":"DEBUG","previous_level":"INFO","message":"..."}
NewHTTPLevelHandler
func NewHTTPLevelHandler(logger *slog.Logger) *HTTPLevelHandler
NewHTTPLevelHandler creates an HTTPLevelHandler for logger. The logger's handler must implement LevelableHandler (i.e. be wrapped with NewLevelHandler); otherwise PUT requests will panic.
HTTPLevelHandler.ServeHTTP
func (h *HTTPLevelHandler) ServeHTTP(w http.ResponseWriter, r *http.Request)
ServeHTTP dispatches GET and PUT; all other methods return 405.
LevelHandler
type LevelHandler struct {
// contains filtered or unexported fields
}
LevelHandler wraps any slog.Handler with a slog.LevelVar for atomic, concurrent-safe runtime level changes. All loggers derived from it via WithAttrs and WithGroup share the same level knob.
NewLevelHandler
func NewLevelHandler(leveler slog.Leveler, h slog.Handler) *LevelHandler
NewLevelHandler wraps h with a LevelVar initialised to leveler.Level(). If h is already a LevelHandler, its inner handler is unwrapped to avoid double-wrapping.
LevelHandler.Enabled
func (h *LevelHandler) Enabled(_ context.Context, level slog.Level) bool
Enabled implements slog.Handler.
LevelHandler.Handle
func (h *LevelHandler) Handle(ctx context.Context, r slog.Record) error
Handle implements slog.Handler.
LevelHandler.Handler
func (h *LevelHandler) Handler() slog.Handler
Handler returns the inner slog.Handler.
LevelHandler.Level
func (h *LevelHandler) Level() slog.Level
Level returns the current active log level.
LevelHandler.SetLevel
func (h *LevelHandler) SetLevel(level slog.Level)
SetLevel changes the active log level. Safe for concurrent use.
LevelHandler.WithAttrs
func (h *LevelHandler) WithAttrs(attrs []slog.Attr) slog.Handler
WithAttrs implements slog.Handler. The returned handler shares the same LevelVar so SetLevel on any sibling adjusts all of them.
LevelHandler.WithGroup
func (h *LevelHandler) WithGroup(name string) slog.Handler
WithGroup implements slog.Handler.
LevelableHandler
type LevelableHandler interface {
slog.Handler
SetLevel(level slog.Level)
}
LevelableHandler is a slog.Handler that supports runtime level changes. Any handler returned by this package implements this interface.
MemSink
type MemSink struct {
// contains filtered or unexported fields
}
MemSink implements telemetry.MetricSink backed by in-memory counters.
NewMemSink
func NewMemSink() *MemSink
NewMemSink returns a MetricSink that stores observations in memory. Useful for development and tests; dump with sink.Snapshot().
MemSink.ContextWithLabels
func (s *MemSink) ContextWithLabels(ctx context.Context, vals ...telemetry.LabelValue) (context.Context, error)
MemSink.NewDistribution
func (s *MemSink) NewDistribution(name, _ string, _ []float64, _ ...telemetry.MetricOption) telemetry.Metric
MemSink.NewGauge
func (s *MemSink) NewGauge(name, _ string, _ ...telemetry.MetricOption) telemetry.Metric
MemSink.NewLabel
func (s *MemSink) NewLabel(name string) telemetry.Label
MemSink.NewSum
func (s *MemSink) NewSum(name, _ string, _ ...telemetry.MetricOption) telemetry.Metric
MemSink.Reset
func (s *MemSink) Reset()
Reset clears all recorded values. Zeroes values in place so existing Metric references (held in package-level vars) stay valid.
MemSink.Snapshot
func (s *MemSink) Snapshot() map[string]float64
Snapshot returns a copy of all recorded values keyed by metric name.
OTelSink
type OTelSink struct {
// contains filtered or unexported fields
}
OTelSink implements telemetry.MetricSink via the OTel metrics SDK.
NewOTelSink
func NewOTelSink(mp *metric.MeterProvider, name string) *OTelSink
NewOTelSink returns a telemetry.MetricSink backed by an OTel MeterProvider. Pass the same MeterProvider you use for Prometheus export; metrics created here flow through the same pipeline.
Call OTelSink.Shutdown on service exit to flush pending metrics.
OTelSink.ContextWithLabels
func (s *OTelSink) ContextWithLabels(ctx context.Context, vals ...telemetry.LabelValue) (context.Context, error)
OTelSink.NewDistribution
func (s *OTelSink) NewDistribution(name, desc string, bounds []float64, opts ...telemetry.MetricOption) telemetry.Metric
OTelSink.NewGauge
func (s *OTelSink) NewGauge(name, desc string, opts ...telemetry.MetricOption) telemetry.Metric
OTelSink.NewLabel
func (s *OTelSink) NewLabel(name string) telemetry.Label
OTelSink.NewSum
func (s *OTelSink) NewSum(name, desc string, opts ...telemetry.MetricOption) telemetry.Metric
OTelSink.Shutdown
func (s *OTelSink) Shutdown(ctx context.Context) error
Shutdown flushes and shuts down the underlying MeterProvider. Call this on service exit, typically via defer or a run.Group actor.