All 42 libraries

SugarMetrics

Telemetry primitives + SugarSshServer session middleware

inspired by charmbracelet/promwish metrics telemetry statsd prometheus

SugarMetrics code coverage

Counters, gauges, histograms, UpDownCounters, AsyncCounters, AsyncGauges with pluggable backends — drop-in middleware for SSH session metrics. Six instrument kinds + five backends: InMemory, JsonStream, StatsD, Prometheus textfile, plus a Multi fan-out. Built-in cardinality tracking with FIFO eviction.

Install

composer require sugarcraft/sugar-metrics

Quickstart

use SugarCraft\Metrics\Registry;
use SugarCraft\Metrics\Backend\StatsdBackend;

$reg = new Registry(new StatsdBackend('127.0.0.1', 8125));

$reg->counter('http.requests', 1, ['route' => '/api/foo', 'status' => '200']);
$reg->gauge  ('queue.depth',  42);

$stop = $reg->time('http.duration', ['route' => '/api/foo']);
// ...do the work being timed (SessionMetrics::handle() wraps exactly this
//     start/stop pattern around the SSH session pipeline, per session)...
$stop();

// Pre-tag every emit:
$req = $reg->withTags(['request_id' => $rid, 'user' => $userId]);
$req->counter('events');

What's in the box

CounterMonotonic value that accumulates (connect counts, errors).
GaugeInstantaneous value that replaces on set (queue depth, RSS).
HistogramDistribution of samples (latency, payload size).
UpDownCounterSynchronous counter supporting positive and negative increments (active connections, queue depth delta).
AsyncCounterAsynchronous counter observed at collection time via callback. External monotonic values (GC counts, bytes served).
AsyncGaugeAsynchronous gauge observed at collection time via callback. External instantaneous readings (memory, queue depth).
Tagged metrics->withTags(['user' => $u]) returns a registry that pre-tags every emit.
Time helper$stop = $reg->time('http.duration'); $stop() — emit a histogram sample on close.
BackendsInMemoryBackend, JsonStreamBackend, StatsdBackend, PrometheusFileBackend, MultiBackend.
Histogram bucketsPrometheus backend emits 14 cumulative le buckets (0.005–100) plus +Inf — the 11 classic client_golang boundaries extended with 25/50/100.
Cardinality trackingFIFO eviction of oldest label combinations when per-metric limit (default 10 000) is exceeded — reclaiming the series on storing backends (InMemory, Prometheus textfile), tracker-only against push-only StatsD/JSON stream arms. Inspect with cardinality().
Descriptor registrationPre-emit # TYPE / # HELP lines before first sample (Prometheus textfile collector metadata).
Untrusted-value trust boundarySSH username/term tags are sanitized to [A-Za-z0-9._:@/-] and clamped to 64 bytes; every backend wire-sweep folds hostile framing tokens (: | ,, space, control/DEL/C1) and the Prometheus writer throws loudly on fold-collisions and two-kind families. Treat untrusted strings as label values, never as metric names.

Source & demos

Try the quickstart →

API

API surface — classes, constructors, and instrument methods.
ClassMethodDescription
Descriptornew(name, help, type, labelKeys)Metric registration DTO (type: counter|gauge|histogram|summary). Names are checked raw — dots are rejected, use underscores
Registrynew(backend, defaultTags, cardinalityLimit)Create a registry from a backend, with default tags merged into every emit and a per-metric cardinality limit (default 10 000)
Registryregister(Descriptor)Register metric descriptor for early TYPE/HELP emission
Registrycounter(name, value, tags)Increment counter
Registrygauge(name, value, tags)Set gauge value
Registryhistogram(name, value, tags)Record a histogram sample (Prometheus backend default: 11 classic client_golang boundaries extended with 25/50/100, plus +Inf)
RegistryupDownCounter(name, amount, tags)Add positive or negative increment to a synchronous up-down counter
RegistryasyncCounter(name, value, tags)Record an observation from an asynchronous counter callback
RegistryasyncGauge(name, value, tags)Record an observation from an asynchronous gauge callback
Registrytime(name, tags)Time a block on the monotonic clock; returns a closer callable
RegistrywithTags(tags)Pre-tag every emit
Registrybackend()Returns the current backend
RegistrycardinalityLimit()The per-metric label-combination budget (constructor argument)
Registrycardinality(name)Number of unique label-value combinations currently tracked for a metric
Registryflush()Publish the backend's state. Stream/socket backends emit as you record and no-op here; a textfile collector is only rewritten inside flush() and nothing in the library arms a timer — always call flush() explicitly from your own schedule
Registryremove(name, tags)Reclaim the tracker entry and — on storing backends — the series (StatsD/JSON-stream remove() is a deliberate no-op; default tags are merged once, exactly as the emit path does)
RegistrydeleteLabelValues(name, tags)Drop a label combination from the cardinality tracker only — backend series are NOT touched; use remove() for a full reclaim (FIFO eviction also runs automatically when the limit is exceeded)
RegistrynewUpDownCounter(name, help, tags)Create a bound UpDownCounter instrument (preferred over constructing the instrument directly)
RegistrynewAsyncCounter(name, help, callback, tags)Create an AsyncCounter observed via callback at collection time
RegistrynewAsyncGauge(name, help, callback, tags)Create an AsyncGauge observed via callback at collection time
UpDownCounteradd(amount, tags)Add positive or negative increment
AsyncCounterobserve(tags)Invoke the callback and record the sum it returned
AsyncGaugeobserve(tags)Invoke the callback and record the instantaneous value it returned
InMemoryBackendnew(maxSamplesPerKey, maxSeries)In-memory storage: per-key histogram reservoir cap (default 4096) and a global series ceiling evicted oldest-first (0 = unbounded)
JsonStreamBackendnew(target, throwOnError)One JSON object per line to a stream or path (default php://stderr); throwOnError = false drops partial-write failures silently
StatsdBackendnew(host, port, dogstatsd, failSilently, timeout, existingSocket)UDP StatsD/DogStatsD; defaults 127.0.0.1:8125, dogstatsd on, failSilently on, 1.0 s open timeout, or pass a pre-made existingSocket
PrometheusFileBackendnew(path, buckets, maxSeriesPerFamily)Prometheus textfile (atomic write; default 14 bucket boundaries — the 11 classic client_golang ones extended with 25/50/100 — plus +Inf; per-family FIFO ceiling, default 10 000)
MultiBackendnew(...backends)Fan out to two or more backends in order; a child failure propagates immediately (fail-fast). Zero children is refused at the door
MultiBackendwithContinueOnError(...backends)Static factory with error isolation: every child gets the emit even if others throw, and the collected failures are rethrown together as one MultiBackendException
MultiBackendExceptionerrors()The array of Throwables collected during a continue-on-error fanout

Demos.

VHS-recorded GIF of the flagship showcase.php example, regenerated by CI on every push that touches the library source. The remaining examples are plain php examples/<name>.php runs — see the examples directory.

Terminal recording of php examples/showcase.php: session counters, gauges and latency samples are recorded, then the collected InMemory totals print.

Counters / gauges / histograms

Registry → InMemoryBackend totals after a tally pass.