telemetry

package
v0.17.1 Latest Latest
Warning

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

Go to latest
Published: May 12, 2026 License: MIT Imports: 6 Imported by: 0

Documentation

Overview

Package telemetry provides the backend-neutral observability primitives that magic core packages (storage, pubsub, logger, and the HTTP middleware) depend on.

The goal of this package is to decouple instrumentation from any particular metrics or tracing backend and to keep the core package import graph small: only OpenTelemetry's trace API, semantic conventions, and propagation packages are allowed transitively. Concrete backends (Prometheus, OTLP) are installed by the observability package during Init.

Until observability.Init runs, a no-op Telemetry is in effect so that instrumented code always has a safe, non-nil target.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func SetGlobal

func SetGlobal(t *Telemetry)

SetGlobal installs t as the process-wide Telemetry. Passing nil resets Global to a no-op Telemetry, which is the correct behavior during observability.Shutdown.

func WarnOnce

func WarnOnce(key, message string, args ...any)

WarnOnce logs a slog warning exactly once per key for the lifetime of the process. It is intended for surfacing soft misconfigurations (for example a non-contextual storage adapter missing trace spans) without repeatedly spamming logs.

The key is the deduplication key; identical keys after the first call are silently dropped. args are passed through to slog as structured attributes.

func WithContext

func WithContext(ctx context.Context, t *Telemetry) context.Context

WithContext returns a context that carries t. FromContext will return t when asked about the returned context (or any derived context). Passing a nil t returns ctx unchanged.

Types

type Counter

type Counter interface {
	Add(value float64, labels ...Label)
}

Counter accumulates monotonic values. Negative Add values are invalid; backends log a one-shot warning and ignore them.

type Gauge

type Gauge interface {
	Set(value float64, labels ...Label)
}

Gauge records an instantaneous value; subsequent Set calls replace the previous value. Modelled on the OpenTelemetry asynchronous gauge but exposed as a synchronous setter for ergonomics.

type Histogram

type Histogram interface {
	Observe(value float64, labels ...Label)
}

Histogram records a distribution of values.

type Label

type Label struct {
	Key   string
	Value string
}

Label is a key/value pair attached to a metric observation. Backends are responsible for normalising the value (for example the Prometheus backend never allows an unset label; callers should pass the empty string rather than omit the label).

func Labels

func Labels(kv ...string) []Label

Labels is a lightweight constructor for a []Label slice from an alternating key/value string list. It mirrors the ergonomics of the slog.Attr helpers so typical call sites read as:

ordersCreated.Add(1, telemetry.Labels(
    "status",  "success",
    "channel", "web",
)...)

Odd-length inputs drop the trailing unpaired key (its value is treated as the empty string). Empty input returns a nil slice so the caller can splat it with ... without introducing a zero-label observation allocation.

type MetricDefinition

type MetricDefinition struct {
	// Name is the fully-qualified metric name (for example
	// "magic_http_requests_total"). Must be non-empty and conform
	// to the Prometheus naming rules: [a-zA-Z_:][a-zA-Z0-9_:]*.
	Name string

	// Help is a short human-readable description of what the
	// metric measures. Required by the Prometheus exposition
	// format and strongly recommended for OTLP.
	Help string

	// Unit is an optional UCUM unit hint.
	Unit Unit

	// Kind identifies the instrument type. Required.
	Kind MetricKind

	// Labels declares the ordered set of label keys that
	// observations are expected to carry. When strict-labels mode
	// is enabled on the backend, observations with keys outside
	// this set are dropped and a one-shot warning is logged.
	// An empty or nil Labels slice means the metric carries no
	// labels.
	Labels []string

	// Buckets is the histogram bucket upper bounds in ascending
	// order. Ignored for non-histogram kinds. When nil the backend
	// applies its built-in default (Prometheus default buckets or
	// the OTEL SDK default view).
	Buckets []float64
}

MetricDefinition declares the shape of a metric at registration time. Backends use this to pre-create instruments and, when strict-labels mode is on, to reject observations that carry label keys outside of Labels.

type MetricKind

type MetricKind int

MetricKind identifies the instrument type of a registered metric.

const (
	// KindCounter is a monotonically-increasing cumulative counter.
	KindCounter MetricKind = iota
	// KindHistogram records a distribution of values.
	KindHistogram
	// KindGauge records an instantaneous value that replaces any
	// previous value.
	KindGauge
	// KindUpDownCounter tracks a sum that can increase or decrease
	// (e.g. in-flight requests, queue depth).
	KindUpDownCounter
)

func (MetricKind) String

func (k MetricKind) String() string

String returns the lowercase name of the kind (for use in diagnostics and error messages).

type MetricsBackend

type MetricsBackend interface {
	Counter(def MetricDefinition) (Counter, error)
	Histogram(def MetricDefinition) (Histogram, error)
	Gauge(def MetricDefinition) (Gauge, error)
	UpDownCounter(def MetricDefinition) (UpDownCounter, error)
}

MetricsBackend creates backend-neutral metric instruments. Implementations must be safe for concurrent use. Instruments returned from the same definition on a given backend must be usable concurrently and may be the same underlying instance (implementations are free to deduplicate).

type Telemetry

type Telemetry struct {
	// Metrics is the backend-neutral metrics factory. Never nil.
	Metrics MetricsBackend
	// Tracer is the OpenTelemetry tracer used to create spans.
	// Never nil; defaults to a no-op tracer.
	Tracer trace.Tracer
}

Telemetry is the container for the observability primitives used by magic core packages. It is intentionally small; additional backends (loggers, profilers) can be added in future releases without breaking callers.

func FromContext

func FromContext(ctx context.Context) *Telemetry

FromContext returns the Telemetry attached to ctx via WithContext, or Global() if none is attached. The returned value is always non-nil.

func Global

func Global() *Telemetry

Global returns the process-wide Telemetry. The returned value is always non-nil; before SetGlobal is called (typically by observability.Init) it is a no-op Telemetry.

func NewNoop

func NewNoop() *Telemetry

NewNoop returns a Telemetry backed by no-op implementations. Safe to use as a zero-configuration default.

type Unit

type Unit string

Unit is a UCUM-style unit hint (for example "s" for seconds, "By" for bytes, "1" for dimensionless). Backends that do not understand the unit ignore it.

const (
	UnitSeconds       Unit = "s"
	UnitBytes         Unit = "By"
	UnitDimensionless Unit = "1"
)

Common units used by built-in magic metrics.

type UpDownCounter

type UpDownCounter interface {
	Add(value float64, labels ...Label)
}

UpDownCounter tracks a value that can go up or down over time (for example in-flight requests or queue depth).

Jump to

Keyboard shortcuts

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