Documentation
¶
Overview ¶
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
Index ¶
- Constants
- func GetAttrs(ctx context.Context) []any
- func GetLogAttrs(ctx context.Context) []any
- func LevelNames() []string
- func LevelSlogValue(l slog.Level) slog.Value
- func LevelString(l slog.Level) string
- func LookupLevel(name string) (slog.Level, error)
- func New(sl *slog.Logger) telemetry.Logger
- func SetAttrs(ctx context.Context, keyValuePairs ...string) context.Context
- func SetLevel(logger *slog.Logger, level slog.Level) *slog.Logger
- func SetLogAttrs(ctx context.Context, keyValuePairs ...string) context.Context
- func TestLogger(tb testing.TB) *slog.Logger
- type Attrs
- type HTTPLevelHandler
- type LevelHandler
- func (h *LevelHandler) Enabled(_ context.Context, level slog.Level) bool
- func (h *LevelHandler) Handle(ctx context.Context, r slog.Record) error
- func (h *LevelHandler) Handler() slog.Handler
- func (h *LevelHandler) Level() slog.Level
- func (h *LevelHandler) SetLevel(level slog.Level)
- func (h *LevelHandler) WithAttrs(attrs []slog.Attr) slog.Handler
- func (h *LevelHandler) WithGroup(name string) slog.Handler
- type LevelableHandler
- type MemSink
- func (s *MemSink) ContextWithLabels(ctx context.Context, vals ...telemetry.LabelValue) (context.Context, error)
- func (s *MemSink) NewDistribution(name, _ string, _ []float64, _ ...telemetry.MetricOption) telemetry.Metric
- func (s *MemSink) NewGauge(name, _ string, _ ...telemetry.MetricOption) telemetry.Metric
- func (s *MemSink) NewLabel(name string) telemetry.Label
- func (s *MemSink) NewSum(name, _ string, _ ...telemetry.MetricOption) telemetry.Metric
- func (s *MemSink) Reset()
- func (s *MemSink) Snapshot() map[string]float64
- type OTelSink
- func (s *OTelSink) ContextWithLabels(ctx context.Context, vals ...telemetry.LabelValue) (context.Context, error)
- func (s *OTelSink) NewDistribution(name, desc string, bounds []float64, opts ...telemetry.MetricOption) telemetry.Metric
- func (s *OTelSink) NewGauge(name, desc string, opts ...telemetry.MetricOption) telemetry.Metric
- func (s *OTelSink) NewLabel(name string) telemetry.Label
- func (s *OTelSink) NewSum(name, desc string, opts ...telemetry.MetricOption) telemetry.Metric
- func (s *OTelSink) Shutdown(ctx context.Context) error
Constants ¶
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
Variables ¶
This section is empty.
Functions ¶
func GetAttrs ¶
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.
func GetLogAttrs ¶ added in v0.2.0
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.
func LevelNames ¶
func LevelNames() []string
LevelNames returns a copy of all supported log level names in ascending order.
func LevelSlogValue ¶
LevelSlogValue returns the pre-allocated slog.Value string for l. Unknown levels return "UNKNOWN".
func LevelString ¶
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).
func LookupLevel ¶
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.
func New ¶
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.
func SetAttrs ¶
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",
)
func SetLevel ¶
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.
func SetLogAttrs ¶ added in v0.2.0
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.
func TestLogger ¶
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.
func TestSomething(t *testing.T) {
logger := log.TestLogger(t)
scope.UseLogger(log.New(logger))
// ... exercise code ...
}
Types ¶
type 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)
func NewAttrs ¶
NewAttrs starts building an Attrs set rooted at ctx. Call Set for each dimension, then Into to stamp them into a new context.
func (*Attrs) Into ¶
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).
type 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":"..."}
func 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.
func (*HTTPLevelHandler) ServeHTTP ¶
func (h *HTTPLevelHandler) ServeHTTP(w http.ResponseWriter, r *http.Request)
ServeHTTP dispatches GET and PUT; all other methods return 405.
type 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.
func 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.
func (*LevelHandler) Handler ¶
func (h *LevelHandler) Handler() slog.Handler
Handler returns the inner slog.Handler.
func (*LevelHandler) Level ¶
func (h *LevelHandler) Level() slog.Level
Level returns the current active log level.
func (*LevelHandler) SetLevel ¶
func (h *LevelHandler) SetLevel(level slog.Level)
SetLevel changes the active log level. Safe for concurrent use.
type LevelableHandler ¶
LevelableHandler is a slog.Handler that supports runtime level changes. Any handler returned by this package implements this interface.
type MemSink ¶
type MemSink struct {
// contains filtered or unexported fields
}
MemSink implements telemetry.MetricSink backed by in-memory counters.
func NewMemSink ¶
func NewMemSink() *MemSink
NewMemSink returns a MetricSink that stores observations in memory. Useful for development and tests; dump with sink.Snapshot().
func (*MemSink) ContextWithLabels ¶
func (*MemSink) NewDistribution ¶
type OTelSink ¶
type OTelSink struct {
// contains filtered or unexported fields
}
OTelSink implements telemetry.MetricSink via the OTel metrics SDK.
func 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.