logging

package module
v0.3.0 Latest Latest
Warning

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

Go to latest
Published: May 12, 2026 License: Apache-2.0 Imports: 16 Imported by: 1 module, 1 package

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.

README

log

Go Reference CI

A slog-backed tetratelabs/telemetry logger optimized for OpenTelemetry, with one guarantee that matters in production:

When you silence logs, metrics still fire.


The problem it solves

In high-traffic services you suppress Info logs to cut noise and cost. The standard pattern breaks when you do that:

// Traditional: two separate calls
log.Info("request handled", "route", route)   // silenced at Error level → gone
requestCounter.Add(ctx, 1)                     // easy to forget

// What actually happens in production when level=Error:
log.Info("request handled", "route", route)   // ← silenced
// requestCounter.Add forgotten               // ← dashboard goes dark

This library fixes it by making log and metric inseparable:

// One call: log + metric always together
logger.Metric(requests).Info("request handled", "route", route)
// level=Error: log silent, metric still fires
// level=Debug: both log and metric fire

The metric fires because RecordContext is called before the level check. For the full reasoning, see RATIONALE.md.


Install

go get github.com/dio/logging

Usage

1. Wire once in main
import (
    "log/slog"

    "github.com/dio/logging"
    "github.com/tetratelabs/telemetry"
    "github.com/tetratelabs/telemetry/scope"
)

// meterProvider is your existing OTel MeterProvider (Prometheus, OTLP, etc.)
sink := log.NewOTelSink(meterProvider, "myapp")
telemetry.SetGlobalMetricSink(sink)
scope.UseLogger(log.New(slog.Default()))
2. Declare metrics in library code

No implementation dependency. Library code only imports the telemetry interface:

var (
    routeLabel telemetry.Label
    requests   telemetry.Metric
    errors     telemetry.Metric
)

func init() {
    telemetry.ToGlobalMetricSink(func(ms telemetry.MetricSink) {
        routeLabel = ms.NewLabel("route")
        requests   = ms.NewSum("app_requests_total",  "Total requests handled")
        errors     = ms.NewSum("app_errors_total",    "Total request errors")
    })
}

var log = scope.Register("server", "HTTP server")
3. Log and emit metrics in one call
// Success path
log.Context(ctx).
    Metric(requests.With(routeLabel.Upsert("/api/v1/users"))).
    Info("request handled", "method", "GET", "status", 200)
// → slog:  level=INFO  msg="request handled" scope=server method=GET status=200
//          trace_id=abc span_id=def  (injected from active OTel span)
// → OTel:  app_requests_total{route="/api/v1/users"} += 1

// Error path
log.Context(ctx).
    Metric(errors.With(routeLabel.Upsert("/api/v1/users"))).
    Error("request failed", err, "method", "GET")
// → slog:  level=ERROR msg="request failed" ... err=context deadline exceeded
// → OTel:  app_errors_total{route="/api/v1/users"} += 1
OTel trace correlation

When a context with an active OTel span is attached via .Context(ctx), trace_id and span_id are automatically injected into every log line without manual extraction:

level=INFO msg="request handled" scope=server trace_id=c02b2a3a... span_id=d1449529... route=/api/v1/users

The same trace_id appears in the OTel trace, making cross-signal correlation trivial.

How it works

logger.Context(ctx) calls trace.SpanFromContext(ctx). If a span is active in the context, its TraceID and SpanID are appended to the logger's key-value pairs before any log call. If no span is active, SpanContext.IsValid() is false and nothing is appended -- no allocation, no overhead.

// Inside slogLogger.Context(ctx):
if sc := trace.SpanFromContext(ctx).SpanContext(); sc.IsValid() {
    c.kvs = append(c.kvs, "trace_id", sc.TraceID().String(), "span_id", sc.SpanID().String())
}
Making a span active

A span must be created by a TracerProvider and stored in the context. Two patterns:

Pattern 1 -- manual span (business logic, background jobs):

tracer := tp.Tracer("myservice")
ctx, span := tracer.Start(r.Context(), "processOrder")
defer span.End()

// ctx now has an active span; trace_id and span_id appear on every log line.
logger.Context(ctx).Info("processing order", "order_id", id)
// Output: level=INFO msg="processing order" trace_id=4bf92... span_id=00f0... order_id=42

Pattern 2 -- middleware (HTTP, gRPC, Connect RPC):

For HTTP servers use go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp; for Connect RPC use connectrpc.com/otelconnect. Both wrap every request with a span and store it in the request context before your handler runs:

// HTTP: otelhttp creates a span per request.
mux.Handle("/api/", otelhttp.NewHandler(apiHandler, "api"))

// Connect RPC: otelconnect creates a span per RPC.
otelInterceptor, _ := otelconnect.NewInterceptor(
    otelconnect.WithTracerProvider(tp),
)
path, handler := myv1connect.NewMyServiceHandler(svc,
    connect.WithInterceptors(otelInterceptor),
)

Your handler receives a ctx that already has a span -- pass it to logger.Context(ctx) and the IDs appear automatically.

Pattern 3 -- no span (plain context):

If you call logger.Context(context.Background()), there is no active span, so no IDs are injected. This is correct and expected -- background goroutines without a trace context simply produce log lines without trace correlation.

See examples/trace/ for a runnable example of all three patterns.


Cross-cutting attributes

Two scopes, picked deliberately based on the cardinality of your values.

Bounded attrs (logs AND metric labels)

Use SetAttrs or NewAttrs for low-cardinality enums like customer ID, environment, service name, region, plan tier. These flow into both log records and metric labels:

// In middleware, once per request (after JWT validation):
ctx = logging.SetAttrs(ctx,
    "customer_id", claims.CustomerID,
    "environment", os.Getenv("ENV"),
    "service_name", "valet",
    "product",      claims.Product,
    "service_plane", "dp",
)

// In library code, no knowledge of the dimensions above:
logger.Context(ctx).Metric(requests).Info("request handled", "route", r.URL.Path)
// log:    msg="request handled" customer_id=acme environment=prod service_name=valet
//         product=tare service_plane=dp trace_id=... span_id=... route=/v1/completions
// metric: requests_total{customer_id="acme",environment="prod",service_name="valet",
//                        product="tare",service_plane="dp"} += 1
Log-only attrs (logs only, never metric labels)

Use SetLogAttrs for unbounded values like request_id, user_id, raw IP, or anything else where the value space is huge:

ctx = logging.SetLogAttrs(ctx,
    "request_id", reqID,
    "user_id", claims.UserID,
)

logger.Context(ctx).Metric(requests).Info("hit")
// log:    msg=hit ... request_id=abc user_id=u-42
// metric: requests_total{customer_id="acme",...} += 1
//         (NO request_id or user_id on the counter)
Why two scopes

OpenTelemetry counters allocate a new time series for every unique combination of label values. A service at 1000 RPS for an hour with request_id on its counters produces 3.6 million series. Cloud Monitoring, Prometheus, and Mimir all bill per series or reject past a hard cap. The counter becomes useless and your metrics backend bills you for the storage.

The fix is keeping unbounded values strictly off counters. Two scopes encode the rule in the API. SetAttrs is for bounded; SetLogAttrs is for unbounded. Same context, different storage, different downstream consumers.

Anti-pattern (this used to be the only option):

// WRONG: request_id leaks to every counter label as a cardinality bomb.
ctx = logging.SetAttrs(ctx,
    "customer_id", claims.CustomerID,
    "request_id", reqID,
)
logger.Context(ctx).Metric(requests).Info("hit")

Correct:

ctx = logging.SetAttrs(ctx, "customer_id", claims.CustomerID)
ctx = logging.SetLogAttrs(ctx, "request_id", reqID)
logger.Context(ctx).Metric(requests).Info("hit")
Builder form

For many bounded dimensions, the builder is cleaner:

ctx = logging.NewAttrs(ctx).
    Set("customer_id", claims.CustomerID).
    Set("environment", env).
    Set("service_name", serviceName).
    Into(ctx)

Calls accumulate: SetAttrs can be called multiple times as more attributes become known. Static service-level attributes (known at startup) belong on the logger via logger.With(...) instead:

// Once in main, service-level static attributes:
base := logging.New(slog.Default()).With(
    "service_name", "valet",
    "environment", os.Getenv("ENV"),
)

// Per-request, dynamic attributes from JWT claims go into context:
ctx = logging.SetAttrs(r.Context(), "customer_id", claims.CustomerID)
base.Context(ctx).Metric(requests).Info("handled")

Runtime log level

Change the active log level without restarting the process. Wire HTTPLevelHandler onto your admin mux once in main:

// Wrap your slog handler with LevelHandler to enable runtime changes.
levelHandler := logging.NewLevelHandler(logging.LevelInfo, slog.NewTextHandler(os.Stderr, nil))
sl := slog.New(levelHandler)

adminMux.Handle("/log/level", logging.NewHTTPLevelHandler(sl))
# Read current level
curl http://localhost:9090/log/level
# {"level":"INFO","available_levels":["DEBUG","INFO","NOTICE","WARNING","ERROR","EMERGENCY"]}

# Change to DEBUG at runtime
curl -X PUT http://localhost:9090/log/level -d '{"level":"DEBUG"}'
# {"level":"DEBUG","previous_level":"INFO","message":"log level changed from INFO to DEBUG"}

Level names are case-insensitive. Aliases are accepted: WARN → WARNING, ERR/FATAL → ERROR.

You can also change the level programmatically:

logging.SetLevel(logger, logging.LevelDebug)

SetLevel panics if the logger's handler was not wrapped with NewLevelHandler. The panic is intentional and fires at startup, not in production.


Sinks

Sink When to use
log.NewOTelSink(mp, name) Production: backed by OTel MeterProvider, exports to Prometheus or OTLP
log.NewMemSink() Tests: in-memory, inspect values with sink.Snapshot()

Testing

Unit tests
go test -race ./...

Uses MemSink without external deps, runs instantly:

sink := log.NewMemSink()
telemetry.SetGlobalMetricSink(sink)
// ...
assert.Equal(t, float64(1), sink.Snapshot()["app_requests_total"])
E2e tests

Uses an in-process OTLP gRPC sink: no Docker, no sleep, precise assertions on exact values and labels:

cd e2e && go test -v -tags e2e -timeout 60s ./...

Assertions look like:

// Exact counter value + label
val, ok := sink.WaitForCounter("app_requests_total", "route", "/api/v1/users", 1, 5*time.Second)

// Log body + trace correlation
rec, ok := sink.WaitForLog("request handled", 5*time.Second)
assert.Equal(t, traceID, rec.Attrs["trace_id"])

// Span by trace ID
span, ok := sink.WaitForSpan(traceID, 5*time.Second)
assert.Equal(t, "GET /api/v1/users", span.Name)
Manual verification with otel-front

For visual browsing of the full telemetry picture, run with otel-front:

# Terminal 1: start otel-front
docker run --rm -p 8000:8000 -p 4317:4317 -p 4318:4318 \
    ghcr.io/mesaglio/otel-front:latest

# Terminal 2: run e2e routing to otel-front
cd e2e && E2E_OTEL_FRONT=1 go test -v -tags e2e -timeout 90s ./...

# Open http://localhost:8000

You will see the same trace_id linking the log record, the metric data point, and the span. The three signals are correlated in one view.


Discussion

Why logger.Context(ctx) instead of passing ctx to every log call

Most logging libraries take ctx as the first argument to every call: logger.InfoContext(ctx, "msg", ...). This library takes a different approach: attach the context once with .Context(ctx), get a new logger, and use it for all calls in that scope.

The difference matters for library code. A component declares:

var log = scope.Register("payments", "payment processing")

and calls log.Info(...) throughout. When the caller wants trace correlation and per-request dimensions, it does:

reqLog := log.Context(ctx)
reqLog.Info("charging card", "amount", amount)
reqLog.Error("charge failed", err)

Both calls carry the same trace_id, span_id, and any SetAttrs dimensions without the library knowing where they come from. The library stays clean; the caller controls what context flows in.

Why metrics fire before the level check
func (l *slogLogger) Info(msg string, kvs ...any) {
    if l.metric != nil {
        l.metric.RecordContext(l.ctx, 1) // always, regardless of level
    }
    if l.level != telemetry.LevelNone && l.level < telemetry.LevelInfo {
        return // log silenced, metric already recorded
    }
    l.sl.Info(msg, l.args(kvs)...)
}

In production you commonly silence Info logs (level=ERROR) to cut noise and cost. If the metric fired after the level check, silencing logs would also silence your alerting signal. The ordering is a deliberate invariant: changing it would silently break every alert that relies on the metric.

See RATIONALE.md for the full reasoning.

When to use With vs SetAttrs

logger.With(kvs...) is for static dimensions known at construction time: service_name, environment, version. They never change and the resulting logger can be stored and reused by concurrent goroutines safely.

SetAttrs(ctx, kvs...) is for dynamic per-request dimensions: customer_id, user_id, product. These differ per request and cannot live on a shared logger without a data race. They live in the context, which is already per-request.

Both reach both logs and metrics. logger.Context(ctx) merges them in order: static With dims first, then context dims, then trace IDs.

// Once at startup:
base := logging.New(sl).With("service", "valet", "env", "prod")

// Per request:
ctx = logging.SetAttrs(r.Context(), "customer_id", claims.CustomerID)
base.Context(ctx).Metric(requests).Info("handled")
// Output: service=valet env=prod customer_id=acme trace_id=... span_id=...
The six severity levels

log/slog defines four levels: DEBUG(-4), INFO(0), WARN(4), ERROR(8). This library adds NOTICE(2) and EMERGENCY(12) to match Google Cloud Logging's severity enum. NOTICE fills the gap between INFO and WARNING for significant-but-normal events (config reload, leadership change). EMERGENCY signals the service is unusable.

Both are available as logging.LevelNotice and logging.LevelEmergency. The gcp/ subpackage maps all six to the Cloud Logging severity strings that GKE and Cloud Run expect.


License

Apache 2.0. See LICENSE.

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

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

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.

func GetLogAttrs added in v0.2.0

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.

func LevelNames

func LevelNames() []string

LevelNames returns a copy of all supported log level names in ascending order.

func LevelSlogValue

func LevelSlogValue(l slog.Level) slog.Value

LevelSlogValue returns the pre-allocated slog.Value string for l. Unknown levels return "UNKNOWN".

func 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).

func 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.

func 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.

func 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",
)

func 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.

func SetLogAttrs added in v0.2.0

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.

func 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.

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

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.

func (*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).

func (*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.

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) Enabled

func (h *LevelHandler) Enabled(_ context.Context, level slog.Level) bool

Enabled implements slog.Handler.

func (*LevelHandler) Handle

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

Handle implements slog.Handler.

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.

func (*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.

func (*LevelHandler) WithGroup

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

WithGroup implements slog.Handler.

type 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.

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 (s *MemSink) ContextWithLabels(ctx context.Context, vals ...telemetry.LabelValue) (context.Context, error)

func (*MemSink) NewDistribution

func (s *MemSink) NewDistribution(name, _ string, _ []float64, _ ...telemetry.MetricOption) telemetry.Metric

func (*MemSink) NewGauge

func (s *MemSink) NewGauge(name, _ string, _ ...telemetry.MetricOption) telemetry.Metric

func (*MemSink) NewLabel

func (s *MemSink) NewLabel(name string) telemetry.Label

func (*MemSink) NewSum

func (s *MemSink) NewSum(name, _ string, _ ...telemetry.MetricOption) telemetry.Metric

func (*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.

func (*MemSink) Snapshot

func (s *MemSink) Snapshot() map[string]float64

Snapshot returns a copy of all recorded values keyed by metric name.

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.

func (*OTelSink) ContextWithLabels

func (s *OTelSink) ContextWithLabels(ctx context.Context, vals ...telemetry.LabelValue) (context.Context, error)

func (*OTelSink) NewDistribution

func (s *OTelSink) NewDistribution(name, desc string, bounds []float64, opts ...telemetry.MetricOption) telemetry.Metric

func (*OTelSink) NewGauge

func (s *OTelSink) NewGauge(name, desc string, opts ...telemetry.MetricOption) telemetry.Metric

func (*OTelSink) NewLabel

func (s *OTelSink) NewLabel(name string) telemetry.Label

func (*OTelSink) NewSum

func (s *OTelSink) NewSum(name, desc string, opts ...telemetry.MetricOption) telemetry.Metric

func (*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.

Directories

Path Synopsis
Package gcp provides a slog handler that formats log records for Google Cloud Logging structured logging.
Package gcp provides a slog handler that formats log records for Google Cloud Logging structured logging.

Jump to

Keyboard shortcuts

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