SugarMetrics
Telemetry primitives + SugarSshServer session middleware
SugarMetrics is a telemetry library for PHP 8.3+ services and terminal apps. It provides counters, gauges, histograms, up-down counters and two callback-driven async instruments, collected by a Registry and sent to one of five backends: in-memory, JSON stream, StatsD, a Prometheus textfile, or a fan-out over several of them. A drop-in middleware records per-session telemetry for sugarcraft/sugar-ssh-server. The instrument model follows the OpenTelemetry metrics API, and the SSH middleware follows charmbracelet/promwish.
Install
composer require sugarcraft/sugar-metrics
Requires PHP 8.3 or newer. The package depends on sugarcraft/sugar-ssh-server, which is needed only by the optional SessionMetrics middleware, and that dependency brings in the ext-ffi requirement. The sibling packages track dev-master, so a project on the default stable minimum stability must set "minimum-stability": "dev" and "prefer-stable": true. Check the platform requirements before wiring metrics into a minimal container image.
Quickstart
use SugarCraft\Metrics\Registry;
$reg = Registry::inMemory(); // accumulates in memory; good for tests and boot probes
$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 ...
$stop(); // records the elapsed seconds as a histogram sample
The same work through instrument objects, which keep their name next to the code that emits them. The help text is published only when the family is also registered with a Descriptor, as described under Troubleshooting:
$requests = $reg->newCounter('http_requests', 'Requests served');
$requests->inc(1.0, ['route' => '/api/foo']);

Concepts and how it works
| Primitive | Behavior |
|---|---|
| Counter | Monotonic total, such as connects or errors. Negative samples are refused. |
| Gauge | Instantaneous value that replaces the previous one on each set, such as queue depth. |
| Histogram | Distribution of samples, such as latency. Negative samples are refused. The Prometheus backend emits 14 cumulative le buckets plus +Inf. |
| UpDownCounter | Synchronous counter that accepts positive and negative increments, such as active connections. |
| AsyncCounter | Counter read through a callback. Call observe() to emit the current external reading. |
| AsyncGauge | Gauge read through a callback, such as memory use or pool size. |
A Registry is the application-facing facade. It forwards each emit to one Backend, and the backend decides how to store or forward the data. A tag is a key/value pair attached to one emit. The Prometheus text format calls the same thing a label, and PrometheusFileBackend translates between the two.
Each unique tag combination is a separate time series. The registry caps the combinations per metric name and evicts the oldest one when the cap is reached. It also asks the backend to release that series, and only storing backends can do that.
Tasks and recipes
Expose a Prometheus textfile
use SugarCraft\Metrics\Registry;
use SugarCraft\Metrics\Backend\PrometheusFileBackend;
$reg = Registry::new(PrometheusFileBackend::new('/var/lib/app/metrics.prom'));
$reg->counter('jobs_done', 1, ['queue' => 'bake']);
$reg->flush(); // writes the textfile atomically, fsync before rename
Stream newline-delimited JSON
use SugarCraft\Metrics\Registry;
$audit = Registry::to('/var/log/app/metrics.json'); // a path, a resource, or php://stderr when null
$audit->gauge('queue.depth', 42);
Fan out to two backends
use SugarCraft\Metrics\Registry;
use SugarCraft\Metrics\Backend\InMemoryBackend;
use SugarCraft\Metrics\Backend\MultiBackend;
use SugarCraft\Metrics\Backend\StatsdBackend;
$memory = new InMemoryBackend();
$reg = Registry::new(MultiBackend::new($memory, StatsdBackend::new('127.0.0.1', 8125)));
$reg->counter('http.requests', 1);
echo $memory->counterValue('http.requests'); // prints 1 (PHP echoes the float 1.0 without a decimal point)
Bound label cardinality
use SugarCraft\Metrics\Registry;
$reg = Registry::new($backend, [], 500); // 500 label combinations per metric name
$reg->cardinality('http.requests'); // current count for this name
$reg->remove('http.requests', ['route' => '/logout']); // drop one series and its backend data
Tag every emit from one request
$req = $reg->withTags(['request_id' => $rid, 'user' => $userId]);
$req->counter('events');
Values from callers you do not trust should be hashed or bucketed before tagging. The backends sweep wire-framing characters, but every distinct value still creates a new series.
Record SSH session telemetry
use SugarCraft\SshServer\Context;
use SugarCraft\SshServer\Middleware;
use SugarCraft\SshServer\Server;
use SugarCraft\SshServer\Session;
use SugarCraft\Metrics\Registry;
use SugarCraft\Metrics\Backend\PrometheusFileBackend;
use SugarCraft\Metrics\Middleware\SessionMetrics;
// The library arms no timers and the textfile is written only on flush() or at
// exit, so a long-lived server must flush after each session itself.
final class FlushMetrics implements Middleware
{
public function __construct(private readonly Registry $registry)
{
}
public function handle(Context $ctx, Session $session, callable $next): void
{
// finally: a session that throws is the one whose error sample must reach the textfile.
$completed = false;
try {
$next($ctx, $session);
$completed = true;
} finally {
try {
$this->registry->flush();
} catch (\Throwable $flushError) {
// A flush failure must not replace the session's own exception;
// on a clean session there is none to protect, so it surfaces.
if ($completed) {
throw $flushError;
}
}
}
}
}
$reg = Registry::new(PrometheusFileBackend::new('/var/lib/ssh/metrics.prom'));
// FlushMetrics is registered first so it wraps SessionMetrics and flushes after
// SessionMetrics has recorded the session's duration and error samples.
Server::new()
->use(new FlushMetrics($reg))
->use(SessionMetrics::new($reg))
->serve();
Long-lived servers must call flush() themselves: the metrics library never does it on a timer, so without a flush per session the textfile shows no ssh_session_* series until the process exits. The shipped examples/ssh-server-with-metrics.php follows the same pattern.
API reference
| Class | Member | Purpose |
|---|---|---|
Registry | new(), inMemory(), to() | Build a registry over a backend, over an InMemoryBackend, or over a JsonStreamBackend. |
Registry | counter(), gauge(), histogram(), upDownCounter(), asyncCounter(), asyncGauge() | Emit one sample directly. |
Registry | newCounter(), newGauge(), newHistogram(), newUpDownCounter(), newAsyncCounter(), newAsyncGauge() | Create a bound instrument. |
Registry | register(), time(), withTags(), flush() | Publish metadata, time a block, derive a tagged child, and push state to the backend. |
Registry | cardinality(), cardinalityLimit(), deleteLabelValues(), remove(), backend() | Inspect and reclaim series. |
Counter, Gauge, Histogram, UpDownCounter | new(), name(), help(), and inc(), set(), observe() or add() | Instrument objects in the Instrument namespace. |
AsyncCounter, AsyncGauge | new(), observe() | Callback-backed instruments in the Instrument namespace. |
Backend | counter, gauge, histogram, upDownCounter, asyncCounter, asyncGauge, describe, flush, remove, clear | Contract every backend implements. |
InMemoryBackend | new(), snapshot(), counterValue(), gaugeValue(), histogramSummary(), histogramValues(), seriesCount() | Holds state in memory for tests and fan-out. |
JsonStreamBackend | new() | Writes one JSON object per emit. |
StatsdBackend | new() | Sends StatsD or DogStatsD datagrams over UDP. |
PrometheusFileBackend | new(), maxSeriesPerFamily() | Writes a Prometheus textfile, with fsync before the atomic rename. |
MultiBackend | new(), withContinueOnError() | Fans each call out to child backends. |
MultiBackendException | errors() | Carries the child failures from a fan-out. |
Descriptor | new() | Name, help text, type and label keys for one metric family. |
SessionMetrics | new(), handle() | SSH middleware that records session connect, duration and error metrics. |
Util | tagKey(), nameToken(), displaySafe(), needsExponentForm() | Helpers for tag keys and wire-safe text. |
Only methods declared in sugar-metrics/src, or inherited from a parent declared there, are listed. A type that extends a class outside that tree, such as \RuntimeException, does not show the methods of that class.
SugarCraft\Metrics
Backend interface
Pluggable metrics emit target.
| Method | Summary |
|---|---|
counter(string $name, float $value, array $tags = []): void | Increment a monotonic counter. |
gauge(string $name, float $value, array $tags = []): void | Set an instantaneous gauge value. |
histogram(string $name, float $value, array $tags = []): void | Record a single sample for a histogram / timer. |
upDownCounter(string $name, float $amount, array $tags = []): void | Add a positive or negative increment to a synchronous up-down counter. |
asyncCounter(string $name, float $value, array $tags = []): void | Record an observation from an asynchronous counter callback. |
asyncGauge(string $name, float $value, array $tags = []): void | Record an observation from an asynchronous gauge callback. |
describe(Descriptor $descriptor): void | Receive a metric descriptor for dialects that support pre-emitted TYPE/HELP metadata (e.g. Prometheus textfile collector). Backends that do not support this may implement as a no-op. |
flush(): void | Flush all pending metric samples to the persistent backend. |
remove(string $name, array $tags = []): void | Remove a specific metric series by name and tags. No-op for backends that do not support removal. |
clear(): void | Reset all accumulated metrics to zero / empty state. No-op for backends that do not support clearing. |
Descriptor final class
Registration DTO for metric descriptors.
| Method | Summary |
|---|---|
static new(string $name, string $help, string $type, array $labelKeys = []): self | House-idiom factory (sugar-metrics-014): Descriptor::new(name:, help:, type:). |
__construct(public readonly string $name, public readonly string $help, public readonly string $type, public readonly array $labelKeys = []) |
Lang final class
Per-library translation facade for sugar-metrics.
Registry final class
Mirrors charmbracelet/promwish Registry (NewRegistry / MustRegister family) — descriptor registration and emit forwarding.
| Method | Summary |
|---|---|
static new(Backend $backend, array $defaultTags = [], int $cardinalityLimit = 10000): self | House-idiom factory (sugar-metrics-014): Registry::new($backend). The constructor stays public and unchanged — this is the additive front door every other SugarCraft class ships. |
static inMemory(array $defaultTags = [], int $cardinalityLimit = 10000): self | One-line default-backend construction (sugar-metrics-045): the test/boot pattern "a registry that just accumulates" used to cost two constructors — Registry::new(InMemoryBackend::new()). Pure sugar over the same front door; every argument forwards unchanged. |
static to($target = null, bool $throwOnError = true, array $defaultTags = [], int $cardinalityLimit = 10000): self | One-line JSON-stream construction (sugar-metrics-045): "a registry writing to stderr/a file" was Registry::new(new JsonStreamBackend( $target)). The target accepts a path string, a stream resource, or null for php://stderr — exactly the JsonStreamBackend front door (resource is not expressible in a signature union, hence the untyped parameter mirroring that class); every argument forwards unchanged. |
__construct(private readonly Backend $backend, array $defaultTags = [], int $cardinalityLimit = 10000, array $descriptors = []) | |
cardinalityLimit(): int | The per-metric label-combination budget (constructor argument). |
flush(): void | Publish the backend's current state (no-op for stream/socket backends that emit as you record). Long-lived servers driving a textfile backend MUST call this on a schedule — the file is only rewritten inside flush(), and nothing in the library arms a timer on the host's event loop. |
register(Descriptor $descriptor): void | Register a metric descriptor for early TYPE/HELP emission. Re-registering the identical (name, type, help, labelKeys) is a no-op; a SECOND, DIFFERENT descriptor for the same name throws — silently keeping the first would let a copy-pasted registration pin stale TYPE/HELP onto an evolving metric. labelKeys are compared in order (the DTO stores the list as given): a reordering is a different declaration and conflicts like any other change. |
counter(string $name, float $value = 1.0, array $tags = []): void | |
gauge(string $name, float $value, array $tags = []): void | |
histogram(string $name, float $value, array $tags = []): void | |
upDownCounter(string $name, float $amount, array $tags = []): void | Add a positive or negative increment to a synchronous up-down counter. |
asyncCounter(string $name, float $value, array $tags = []): void | Record an observation from an asynchronous counter callback. |
asyncGauge(string $name, float $value, array $tags = []): void | Record an observation from an asynchronous gauge callback. |
newCounter(string $name, string $help = '', array $tags = []): Instrument\Counter | Factory: create a new Counter instrument for repeated inc() calls. sugar-metrics-021 symmetry: the three most-used kinds are now as holdable as UpDownCounter/AsyncCounter/AsyncGauge. |
newGauge(string $name, string $help = '', array $tags = []): Instrument\Gauge | Factory: create a new Gauge instrument for repeated set() calls. |
newHistogram(string $name, string $help = '', array $tags = []): Instrument\Histogram | Factory: create a new Histogram instrument for repeated observe() calls. |
newUpDownCounter(string $name, string $help = '', array $tags = []): Instrument\UpDownCounter | Factory: create a new UpDownCounter instrument for repeated add() calls. |
newAsyncCounter(string $name, string $help, \Closure $callback, array $tags = []): Instrument\AsyncCounter | Factory: create a new AsyncCounter instrument. Nothing collects on a schedule — call $instrument->observe() yourself (typically from your own periodic tick or a shutdown hook) to sample the callback now. |
newAsyncGauge(string $name, string $help, \Closure $callback, array $tags = []): Instrument\AsyncGauge | Factory: create a new AsyncGauge instrument. Nothing collects on a schedule — call $instrument->observe() yourself to sample the callback (an exporter's scrape cadence lives in the host, not here). |
time(string $name, array $tags = []): callable | Start an elapsed-time timer. Returns a closure — when invoked, it records the elapsed seconds as a histogram under $name. The pair reads the monotonic clock (hrtime()), not wall time: a system clock step (NTP correction, manual set) can never turn a duration negative in a finally arm that rethrows. |
withTags(array $tags): self | Returns a child registry whose every emit is pre-tagged with $tags (merged on top of the existing defaults). |
backend(): Backend | |
cardinality(string $name): int | Number of unique label-value combinations currently tracked for $name. |
deleteLabelValues(string $name, array $tags = []): void | Drop one label-combination entry from the cardinality tracker. |
remove(string $name, array $tags = []): void | Remove a specific metric series from the backend and the cardinality cache. Useful for long-running processes or testing cleanup. Backends that keep no retained state (StatsD, JSON stream) treat the removal as a no-op; the tracker entry is always dropped. |
Util final class
Shared utility functions for the metrics library.
| Method | Summary |
|---|---|
static tagKey(array $tags): string | Sort tags by key and build a stable, collision-free k=v|k2=v2 string. Every key and value is backslash-escaped first (\ → \\, | → \|, = → \=), so a separator that appears inside a tag payload cannot impersonate the pair delimiter: without it, ['x' => 'a|y=b'] and ['x' => 'a', 'y' => 'b'] would serialize identically and collapse two distinct series into one cardinality slot. |
static nameToken(string $name): string | The storage-key NAME segment gets the identical escape a tag token gets (see self::escapeTagToken()). In-memory accumulation accepts arbitrary raw names — there is no sanitize-name gate on that path — so without this the name 'x|y=1' would land in exactly the bucket 'x' + tags ['y' => '1'] folds into (finding 013). One escaper for every segment makes the separator unforgeable from both sides, and the map stays readable: a clean name escapes to itself, so the storage key of every well-behaved series is unchanged. |
static nonFiniteToken(float $value): ?string | Canonical exposition spellings for non-finite readings. |
static needsExponentForm(float $value): bool | True when the fixed six-decimal rendering would lie: magnitudes beyond the integer-precision band print noise, and non-zero values below 1e-6 collapse to "0.000000" (a sub-microsecond timed() span reporting a zero sum). Exponent form keeps both honest. |
static displaySafe(string $text): string | Sweep terminal-control bytes out of a string that is about to be interpolated into an exception message. TUI hosts print throwable messages verbatim, and metric names/paths are operator- (or in the SSH middleware, attacker-) controlled — delegating to the shared sugar-core display sanitizer keeps the sweep consistent fleet-wide. |
SugarCraft\Metrics\Backend
InMemoryBackend final class
In-memory accumulator. Counters add up, gauges hold the latest value, histograms keep a bounded reservoir of samples. Mostly used for tests and for fanning out to multiple "live" backends via MultiBackend.
| Method | Summary |
|---|---|
static new(int $maxSamplesPerKey = 4096, int $maxSeries = 0): self | House-idiom factory (sugar-metrics-014): InMemoryBackend::new(). |
__construct(private readonly int $maxSamplesPerKey = 4096, private readonly int $maxSeries = 0) | |
counter(string $name, float $value, array $tags = []): void | |
gauge(string $name, float $value, array $tags = []): void | |
histogram(string $name, float $value, array $tags = []): void | |
upDownCounter(string $name, float $amount, array $tags = []): void | |
asyncCounter(string $name, float $value, array $tags = []): void | |
asyncGauge(string $name, float $value, array $tags = []): void | |
describe(Descriptor $descriptor): void | |
flush(): void | |
counters(): array | |
gauges(): array | |
histograms(): array | |
upDownCounters(): array | |
asyncCounters(): array | |
asyncGauges(): array | |
snapshot(): array | Structured read surface (sugar-metrics-022): every accumulated series as its own row, with the internal storage key decoded back into the faithful name + tags the caller emitted. The raw maps above stay for zero-copy access, but they are keyed by the self::key() grammar — consumers parsing name|k=v by hand re-implement the escaper wrong exactly when a payload carries a separator (an adversar- ial name like 'x|y=1' is indistinguishable from a fold once you split naively), and histogram consumers re-implement the reservoir aggre- gation. Additive: no existing behavior moves. |
histogramSummary(string $name, array $tags = []): ?array | Aggregate view of one histogram series, or null when the series is absent. count/sum/mean describe the RETAINED RESERVOIR (bounded at maxSamplesPerKey); observed is the total number of samples ever seen for the series, so post-cap the two axes are honestly distinct — a reservoir mean is not a stream mean, and pretending otherwise would just move the consumer-boilerplate problem inside the library. |
counterValue(string $name, array $tags = []): float | |
gaugeValue(string $name, array $tags = []): ?float | |
histogramValues(string $name, array $tags = []): array | |
upDownCounterValue(string $name, array $tags = []): float | |
asyncCounterValue(string $name, array $tags = []): float | |
asyncGaugeValue(string $name, array $tags = []): ?float | |
clear(): void | Reset all accumulated metrics to zero. Useful for long-running processes or test cleanup. |
maxSamplesPerKey(): int | Configured upper bound on retained histogram samples per series. |
maxSeries(): int | Configured upper bound on distinct series (0 = unbounded). |
seriesCount(): int | Current number of distinct series held. |
remove(string $name, array $tags = []): void | Remove a specific metric series by name and tags. Removes from whichever accumulator(s) hold a value for that key. |
JsonStreamBackend final class
Newline-delimited JSON emitter. Every metric event gets a fresh line on the underlying stream (file, php://stderr, a socket). The simplest and most diagnostic-friendly backend — tail -f / jq away.
| Method | Summary |
|---|---|
static new($target = null, bool $throwOnError = true): self | House-idiom factory (sugar-metrics-014): JsonStreamBackend::new($target). |
__construct($target = null, bool $throwOnError = true) | |
__destruct() | |
counter(string $name, float $value, array $tags = []): void | |
gauge(string $name, float $value, array $tags = []): void | |
histogram(string $name, float $value, array $tags = []): void | |
upDownCounter(string $name, float $amount, array $tags = []): void | |
asyncCounter(string $name, float $value, array $tags = []): void | |
asyncGauge(string $name, float $value, array $tags = []): void | |
describe(Descriptor $descriptor): void | |
flush(): void | |
remove(string $name, array $tags = []): void | JSON stream backend has no in-memory accumulation; metrics are already written to the stream and cannot be retracted. |
clear(): void | JSON stream backend has no in-memory accumulation to clear. |
MultiBackend final class
Fanout to multiple backends. Useful for emitting to the live StatsD/Prometheus pipeline AND keeping a JSON audit trail at the same time, or for combining an in-memory tally with a production sink in tests.
| Method | Summary |
|---|---|
static new(Backend ...$children): self | House-idiom factory (sugar-metrics-014): MultiBackend::new($a, $b). The continue-on-error posture is still flipped with the immutable withContinueOnError() — new() builds, with*() adjusts. |
__construct(Backend ...$children) | |
static withContinueOnError(Backend ...$children): self | Factory: create a new MultiBackend with error isolation enabled. When enabled, every child receives the emit call even if a prior child throws; all failures are collected and rethrown as one RuntimeException after the fanout completes. |
counter(string $name, float $value, array $tags = []): void | |
gauge(string $name, float $value, array $tags = []): void | |
histogram(string $name, float $value, array $tags = []): void | |
upDownCounter(string $name, float $amount, array $tags = []): void | |
asyncCounter(string $name, float $value, array $tags = []): void | |
asyncGauge(string $name, float $value, array $tags = []): void | |
describe(Descriptor $descriptor): void | |
remove(string $name, array $tags = []): void | |
clear(): void | |
flush(): void |
MultiBackendException final class
Thrown by MultiBackend when multiple child backends fail during a fanout operation in continue-on-error mode.
| Method | Summary |
|---|---|
static new(array $errors, string $message = ''): self | House-idiom factory (sugar-metrics-014): MultiBackendException::new($errors). |
__construct(private readonly array $errors, string $message = '') | |
errors(): array | Returns all errors collected during the fanout. |
PrometheusFileBackend final class
Mirrors charmbracelet/promwish textfile collector output path (the node_exporter --collector.textfile.directory pattern).
| Method | Summary |
|---|---|
static new(string $path, ?array $buckets = null, int $maxSeriesPerFamily = self::DEFAULT_MAX_SERIES_PER_FAMILY, ?int $fileMode = null): self | House-idiom factory (sugar-metrics-014): PrometheusFileBackend::new($path). |
__construct(private readonly string $path, ?array $buckets = null, private readonly int $maxSeriesPerFamily = self::DEFAULT_MAX_SERIES_PER_FAMILY, ?int $fileMode = null) | |
maxSeriesPerFamily(): int | The per-family series budget this backend enforces (constructor argument). |
__destruct() | |
counter(string $name, float $value, array $tags = []): void | |
gauge(string $name, float $value, array $tags = []): void | |
histogram(string $name, float $value, array $tags = []): void | |
upDownCounter(string $name, float $amount, array $tags = []): void | |
asyncCounter(string $name, float $value, array $tags = []): void | |
asyncGauge(string $name, float $value, array $tags = []): void | |
describe(Descriptor $descriptor): void | |
flush(): void | |
remove(string $name, array $tags = []): void | Drop one accumulated series (name + label set) from the backend's in-memory state, plus its collision-detector records and family index entry. The storage key is derived exactly like the write path, so this reclaims what counter()/gauge()/histogram()/... stored — including the Registry's cardinality-eviction forward, which arrives with the merged tag set. The next flush() simply no longer emits the removed series; the textfile itself is rewritten whole on every flush, so no stale line survives. remove() consults the same collision record the write path keeps: a call whose raw (name, tags) is NOT the identity recorded under that folded key would reach through the fold and silently wipe an innocent twin, so it is refused exactly like a colliding write; the honest reclaim drops the record with the series, freeing the fold for the twin to claim later. |
clear(): void | Reset the backend: forget every accumulated series, dirty flag, collision record, family index entry, and registered descriptor. The next flush() writes an empty textfile (the file itself is not unlinked — deleting the target from under a watching node_exporter is a deployment decision, not a metrics-library one). |
StatsdBackend final class
Mirrors charmbracelet/promwish statsd reporter family (the WithStatsd option and its wire formatter).
| Method | Summary |
|---|---|
static new(string $host = '127.0.0.1', int $port = 8125, bool $dogstatsd = true, bool $failSilently = true, float $timeout = 1.0, mixed $existingSocket = null): self | House-idiom factory (sugar-metrics-014): StatsdBackend::new(). |
__construct(string $host = '127.0.0.1', int $port = 8125, private readonly bool $dogstatsd = true, private readonly bool $failSilently = true, float $timeout = 1.0, mixed $existingSocket = null) | |
__destruct() | |
counter(string $name, float $value, array $tags = []): void | |
gauge(string $name, float $value, array $tags = []): void | |
histogram(string $name, float $value, array $tags = []): void | |
upDownCounter(string $name, float $amount, array $tags = []): void | |
asyncCounter(string $name, float $value, array $tags = []): void | |
asyncGauge(string $name, float $value, array $tags = []): void | |
describe(Descriptor $descriptor): void | |
flush(): void | |
remove(string $name, array $tags = []): void | StatsD is fire-and-forget; metrics cannot be removed once sent. |
clear(): void | StatsD is fire-and-forget; the only retained state is the bounded per-token fold cache (sugar-metrics-015), dropped here with the call. |
SugarCraft\Metrics\Instrument
AsyncCounter final class
An asynchronous instrument that reports a monotonically increasing sum. The supplied callback is invoked when you call observe() — the library arms no collection timer of its own, so a periodic tick (or your scrape/mirror loop) is what samples the external value.
| Method | Summary |
|---|---|
static new(Registry $registry, string $name, string $help, \Closure $callback, array $tags = []): self | House-idiom factory (sugar-metrics-014): forward-to-ctor while the constructor stays public (privatization is the gated MET-PRIVATECTOR). |
__construct(private readonly Registry $registry, private readonly string $name, private readonly string $help, private readonly \Closure $callback, private readonly array $tags = []) | |
observe(array $tags = []): void | Sample the callback once and record the returned sum. |
name(): string | |
help(): string |
AsyncGauge final class
An asynchronous instrument that reports a non-monotonic instantaneous value. The supplied callback is invoked when you call observe() — the library arms no collection timer of its own, so a periodic tick (or your scrape/mirror loop) is what samples the external value.
| Method | Summary |
|---|---|
static new(Registry $registry, string $name, string $help, \Closure $callback, array $tags = []): self | House-idiom factory (sugar-metrics-014): forward-to-ctor while the constructor stays public (privatization is the gated MET-PRIVATECTOR). |
__construct(private readonly Registry $registry, private readonly string $name, private readonly string $help, private readonly \Closure $callback, private readonly array $tags = []) | |
observe(array $tags = []): void | Sample the callback once and record the returned gauge reading. |
name(): string | |
help(): string |
Counter final class
A monotonic counter — a value that only ever goes up (requests served, jobs completed). Symmetry for the most-used kind (sugar-metrics-021): hold it once with its static tags and call inc() everywhere instead of restating the tag array per call site.
| Method | Summary |
|---|---|
static new(Registry $registry, string $name, string $help = '', array $tags = []): self | House-idiom factory (sugar-metrics-014): forward-to-ctor while the constructor stays public (privatization is the gated MET-PRIVATECTOR). |
__construct(private readonly Registry $registry, private readonly string $name, private readonly string $help = '', private readonly array $tags = []) | |
inc(float $by = 1.0, array $tags = []): void | Add $by to the counter. The verb-level monotonic guard (Registry::counter) refuses negative amounts at the door; the instrument does not fork a second check. |
name(): string | |
help(): string |
Gauge final class
A gauge — a value that can go up and down freely (queue depth, temperature, memory in use). Symmetry for the most-used kinds (sugar-metrics-021): hold it once with its static tags and call set() everywhere instead of restating the tag array per call site.
| Method | Summary |
|---|---|
static new(Registry $registry, string $name, string $help = '', array $tags = []): self | House-idiom factory (sugar-metrics-014): forward-to-ctor while the constructor stays public (privatization is the gated MET-PRIVATECTOR). |
__construct(private readonly Registry $registry, private readonly string $name, private readonly string $help = '', private readonly array $tags = []) | |
set(float $value, array $tags = []): void | Set the gauge to $value (last write wins). Negative values are legitimate for gauges — no monotonic guard applies. |
name(): string | |
help(): string |
Histogram final class
A histogram — a distribution of observed values (latencies, body sizes) recorded into buckets. Symmetry for the most-used kinds (sugar-metrics-021): hold it once with its static tags and call observe() everywhere instead of restating the tag array per call site.
| Method | Summary |
|---|---|
static new(Registry $registry, string $name, string $help = '', array $tags = []): self | House-idiom factory (sugar-metrics-014): forward-to-ctor while the constructor stays public (privatization is the gated MET-PRIVATECTOR). |
__construct(private readonly Registry $registry, private readonly string $name, private readonly string $help = '', private readonly array $tags = []) | |
observe(float $value, array $tags = []): void | Record one observation. The verb-level negative guard (Registry::histogram) refuses samples below every bucket boundary; the instrument does not fork a second check. |
name(): string | |
help(): string |
UpDownCounter final class
A synchronous instrument that adds positive and negative increments — used when a value can go up or down (e.g., active connections, item counts in a queue).
| Method | Summary |
|---|---|
static new(Registry $registry, string $name, string $help = '', array $tags = []): self | House-idiom factory (sugar-metrics-014): forward-to-ctor while the constructor stays public (privatization is the gated MET-PRIVATECTOR). |
__construct(private readonly Registry $registry, private readonly string $name, private readonly string $help = '', private readonly array $tags = []) | |
add(float $amount, array $tags = []): void | Add $amount to the current value. Positive increments increase the sum; negative increments decrease it. |
name(): string | |
help(): string |
SugarCraft\Metrics\Middleware
SessionMetrics final class
Mirrors charmbracelet/promwish middleware option (the InstrumentHandler pattern): wraps a handler to emit telemetry around each invocation.
| Method | Summary |
|---|---|
static new(Registry $registry, ?callable $extraTags = null, bool $fullExceptionClass = false): self | House-idiom factory (sugar-metrics-014): SessionMetrics::new($registry). |
__construct(private readonly Registry $registry, ?callable $extraTags = null, private readonly bool $fullExceptionClass = false) | |
handle(Context $ctx, Session $session, callable $next) |
Configuration and options
| Constructor | Option | Default | Effect |
|---|---|---|---|
Registry::new() | $defaultTags | [] | Tags merged into every emit. |
Registry::new() | $cardinalityLimit | 10 000 | Series per metric name. Values below 1 throw InvalidArgumentException. |
InMemoryBackend::new() | $maxSamplesPerKey | 4 096 | Histogram reservoir size per series. |
InMemoryBackend::new() | $maxSeries | 0 (uncapped) | Total series. When set, the oldest is dropped first. |
PrometheusFileBackend::new() | $buckets | 14 default buckets | Histogram bucket boundaries. |
PrometheusFileBackend::new() | $maxSeriesPerFamily | 10 000 | Series per family. The oldest is dropped first. |
PrometheusFileBackend::new() | $fileMode | 0600 | Permissions on the textfile. |
StatsdBackend::new() | $host, $port | 127.0.0.1, 8125 | Destination of the datagrams. |
StatsdBackend::new() | $dogstatsd, $failSilently, $timeout | true, true, 1.0 | DogStatsD framing, whether send errors are swallowed, and the socket timeout in seconds. |
JsonStreamBackend::new() | $target, $throwOnError | null, true | Output stream, and whether write failures throw. |
SessionMetrics::new() | $extraTags, $fullExceptionClass | null, false | A callable adding tags per session, and whether the exception tag carries the full class name. |
Examples
examples/showcase.phprecords counters, gauges and histogram samples into an in-memory backend, so it runs with no StatsD or Prometheus setup. It prints the counter and gauge values and the histogram summaries.examples/ssh-server-with-metrics.phpruns a SugarSshServer withSessionMetrics, sending session telemetry to a Prometheus textfile and to an in-memory backend.
Run an example from the package root with php examples/showcase.php.
Testing
Run the suite from the package root with vendor/bin/phpunit. The suite covers the registry and its cardinality tracking, each instrument, each backend, the middleware, the descriptor rules and the locale catalogs. ExampleSmokeTest lints both examples and runs the showcase to completion.
Troubleshooting and FAQ
RuntimeException: a metric name is registered twice with different metadata
Registry::register() accepts a re-registration only when the type, help text and label keys all match. Any difference throws a RuntimeException. Give the metric one Descriptor and reuse it.
InvalidArgumentException for a descriptor name containing a dot
A Descriptor name must match [a-zA-Z_:][a-zA-Z0-9_:]*, so http.requests is refused. The emit path can keep the dotted name, but on the Prometheus wire it becomes http_requests. Register the underscore form with a descriptor, as in $reg->register(Descriptor::new('http_requests', 'Requests served', 'counter')), to publish # TYPE and # HELP lines before the first emit. The instrument returned by newCounter() keeps its help text but does not register it, so newCounter('http_requests', 'Requests served') alone never publishes the # HELP line.
RuntimeException on a negative counter or histogram sample
Counters and histograms are monotonic in the sense that they refuse negative samples. Use upDownCounter() for a value that rises and falls, such as active connections, or a gauge for an instantaneous reading.
RuntimeException about two series that fold to the same Prometheus name
Prometheus names cannot contain most punctuation, so PrometheusFileBackend folds names and label keys. When two distinct raw names fold to the same key, it throws rather than merging them. Rename one of the metrics so the folded names differ.
The textfile shows no samples for a family
The file shows a family only after its first sample, unless it was registered with a Descriptor. Register the descriptor on the registry to publish the # TYPE and # HELP lines before the first sample arrives.
Memory keeps growing on StatsD or JSON output
Eviction releases series from storing backends such as InMemoryBackend and PrometheusFileBackend. StatsdBackend and JsonStreamBackend have already sent what they emitted, so their remove() is a no-op. Against those backends the cardinality limit bounds only the registry's own tracker.
Upstream mapping
| Upstream | SugarMetrics | Notes |
|---|---|---|
| OpenTelemetry metrics API (opentelemetry.io/api/metrics) | Instrument\Counter, Gauge, Histogram, UpDownCounter, AsyncCounter, AsyncGauge | The instrument docblocks cite this API. |
| charmbracelet/promwish (Go) | Middleware\SessionMetrics, Backend\PrometheusFileBackend, Backend\StatsdBackend | The SSH middleware and the textfile and StatsD reporters mirror promwish's option and output shapes. |
Changelog and versioning
The package ships no separate changelog file. It is published from the monorepo with the other sugarcraft/* packages on dev-master. Breaking changes are recorded in the README under Breaking changes. For example, the multi-backend exception's error accessor is now the bare errors() method, following the bare-accessor convention; code that still calls the earlier get-prefixed accessor must switch.