SugarMetrics
Telemetry primitives + SugarSshServer session middleware
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
- Source on GitHub
- Full README
- Runnable examples
- Originally inspired by promwish (Go); SugarCraft is developed as a native PHP project.
API
| Class | Method | Description |
|---|---|---|
| Descriptor | new(name, help, type, labelKeys) | Metric registration DTO (type: counter|gauge|histogram|summary). Names are checked raw — dots are rejected, use underscores |
| Registry | new(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) |
| Registry | register(Descriptor) | Register metric descriptor for early TYPE/HELP emission |
| Registry | counter(name, value, tags) | Increment counter |
| Registry | gauge(name, value, tags) | Set gauge value |
| Registry | histogram(name, value, tags) | Record a histogram sample (Prometheus backend default: 11 classic client_golang boundaries extended with 25/50/100, plus +Inf) |
| Registry | upDownCounter(name, amount, tags) | Add positive or negative increment to a synchronous up-down counter |
| Registry | asyncCounter(name, value, tags) | Record an observation from an asynchronous counter callback |
| Registry | asyncGauge(name, value, tags) | Record an observation from an asynchronous gauge callback |
| Registry | time(name, tags) | Time a block on the monotonic clock; returns a closer callable |
| Registry | withTags(tags) | Pre-tag every emit |
| Registry | backend() | Returns the current backend |
| Registry | cardinalityLimit() | The per-metric label-combination budget (constructor argument) |
| Registry | cardinality(name) | Number of unique label-value combinations currently tracked for a metric |
| Registry | flush() | 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 |
| Registry | remove(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) |
| Registry | deleteLabelValues(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) |
| Registry | newUpDownCounter(name, help, tags) | Create a bound UpDownCounter instrument (preferred over constructing the instrument directly) |
| Registry | newAsyncCounter(name, help, callback, tags) | Create an AsyncCounter observed via callback at collection time |
| Registry | newAsyncGauge(name, help, callback, tags) | Create an AsyncGauge observed via callback at collection time |
| UpDownCounter | add(amount, tags) | Add positive or negative increment |
| AsyncCounter | observe(tags) | Invoke the callback and record the sum it returned |
| AsyncGauge | observe(tags) | Invoke the callback and record the instantaneous value it returned |
| InMemoryBackend | new(maxSamplesPerKey, maxSeries) | In-memory storage: per-key histogram reservoir cap (default 4096) and a global series ceiling evicted oldest-first (0 = unbounded) |
| JsonStreamBackend | new(target, throwOnError) | One JSON object per line to a stream or path (default php://stderr); throwOnError = false drops partial-write failures silently |
| StatsdBackend | new(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 |
| PrometheusFileBackend | new(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) |
| MultiBackend | new(...backends) | Fan out to two or more backends in order; a child failure propagates immediately (fail-fast). Zero children is refused at the door |
| MultiBackend | withContinueOnError(...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 |
| MultiBackendException | errors() | 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.