Expand description
Collects Prometheus-compatible metrics and returns them as structured Rust values.
metrics-collector-prometheus implements metrics::Recorder, aggregating counters,
gauges, summaries, classic histograms, and Prometheus native histograms as an application
records them through the metrics facade. Calling collect
hands back an owned, deterministically ordered
MetricSnapshot.
§What this crate is not
- Not an exporter. It renders no bytes: no Prometheus text exposition format, no
protobuf encoding.
MetricSnapshotis the product; encoding it onto a wire is left to the caller. - Not a transport. There is no HTTP listener and no push gateway.
- Not a runtime.
buildandinstallreturn synchronously and spawn nothing. The one place a background thread exists at all is opt-in and explicit – see “Upkeep” below.
This is a fork of metrics-exporter-prometheus, which does all three. See the
README for why this fork exists and for the full list of behavioral divergences from it.
§Usage
use metrics_collector_prometheus::PrometheusCollectorBuilder;
// Install sets the process-global `metrics::Recorder`; call it once, near your
// program's entry point. `handle` is how you read data back out later.
let handle = PrometheusCollectorBuilder::new().install().expect("failed to install collector");
metrics::counter!("requests").increment(1);
let snapshot = handle.collect();
let family = &snapshot.families[0];
assert_eq!(family.name, "requests"); // raw -- see "Names and labels are raw" belowPrefer not to touch the global recorder? Build one directly and pass it to
metrics::with_local_recorder, or combine it with other recorders yourself:
use metrics_collector_prometheus::PrometheusCollectorBuilder;
let recorder = PrometheusCollectorBuilder::new().build();
let handle = recorder.handle();
metrics::with_local_recorder(&recorder, || {
metrics::gauge!("in_flight_requests").set(3.0);
});
assert_eq!(handle.collect().families.len(), 1);§Names and labels are raw
MetricFamily::name and
LabelPair’s fields hold exactly what was registered: sanitized to
be valid Prometheus identifiers, but not decorated. Nothing here appends _total, inserts
a unit, or escapes a label value. That is naming::exposition_name’s job for names, and
LabelPair::exposition_label /
exposition_value’s job for labels – applied on
demand by whichever consumer needs Prometheus’s rules. A consumer targeting a different wire
format is never forced to undo them.
§Upkeep
Nothing here spawns a background task on its own. Histogram samples accumulate in a bounded
queue and are aggregated into a snapshot-ready form only when drained, which
collect does as a side effect. A process that collects
regularly needs nothing else. A process that collects rarely, or not at all, should call
CollectorHandle::run_upkeep on its own schedule, or use
CollectorHandle::spawn_upkeep to run it on a dedicated thread – see that method and
UpkeepGuard for what dropping the returned guard costs.
§The serde feature
With serde enabled, every type in snapshot implements Serialize and Deserialize,
under a compatibility contract meant to outlive any one version of this crate:
- Adding a field to an existing struct is not a breaking change in either direction. New
fields are
#[serde(default)]; an older reader skips fields it does not know. - Adding a variant to
MetricValueorMetricKindis not a breaking change to compile against, but an older reader’s deserializer fails with a hardunknown varianterror on a payload containing the new variant, rather than silently discarding the sample. SeeMetricValue’s own documentation for why a fallback variant was rejected. - An unrecognized
metrics::Unitstring onMetricFamily::unitis also a hard error, and it fails the entire snapshot’s deserialization, not just the one family carrying it –Unithas no fallback variant to fall back to.
In short: a snapshot stored today always parses with a newer version of this crate; a newer snapshot parses with an older version only if it used no variant, and no unit, the older version lacks.
This contract holds only for self-describing formats – JSON, YAML, CBOR, and similar,
where the wire format itself encodes each value’s type. MetricValue::Gauge
and every other non-finite-capable f64 field (Bucket::upper_bound,
summary/histogram sums, and native-histogram thresholds) round-trip through a
#[serde(untagged)] bridge that encodes a non-finite value as a string ("NaN",
"Infinity", "-Infinity") instead of a number, so the deserializer can accept either shape.
#[serde(untagged)] requires Deserializer::deserialize_any, which non-self-describing
binary formats – bincode, postcard, MessagePack in its compact/non-human-readable
mode – do not implement. Against one of those, deserializing a MetricSnapshot fails
outright, and, worse, serializing one silently succeeds while producing a byte
stream whose per-value shape (number vs. string) depends on whether that particular value
happened to be finite – not a stable schema. Stick to a self-describing format for anything
serialized with this crate’s serde support.
Modules§
- naming
- Sanitization and naming policy for Prometheus metric names, label keys, and label values.
- snapshot
- Format-agnostic structured representation of a Prometheus metrics snapshot.
Structs§
- Collector
Handle - Handle for accessing metrics stored via
PrometheusCollector. - Native
Histogram Config - Configuration for native histograms.
- Prometheus
Collector - A Prometheus recorder.
- Prometheus
Collector Builder - Builder for creating and installing a Prometheus recorder.
- Upkeep
Guard - Stops the background upkeep thread when dropped.
Enums§
- Build
Error - Errors that could occur while building or installing a Prometheus recorder.
- Matcher
- Matches a metric name in a specific way.