Expand description
Prometheus-style metrics for no_std embedded devices, with no heap
allocation.
§Declaring metrics
Each crate/binary declares the metrics it exports with metrics!,
inside a dedicated module. It expands to a real Metrics struct (one field
per metric, so IDE autocomplete and find-usages work at call sites), a
METRICS static, a get() accessor, and the internal registration metadata
used by the renderer.
/// Wi-Fi driver metrics.
pub mod metrics {
embeprom::metrics! {
namespace = "wifi";
/// Total Wi-Fi frames transmitted.
packets_sent: Counter,
/// Last measured RSSI in dBm.
rssi_dbm: Gauge,
/// Disconnects, by reason.
#[labels("reason")]
disconnects_total: CounterVec<4>,
/// TX completion latency in microseconds.
#[buckets(100, 500, 1000, 5000)]
tx_latency_us: IntHistogram,
}
}
// Anywhere in the crate, with no collector object to thread through, and
// no separate registration step: the first call to `metrics::get()`
// registers the group with the global registry (see "Registration" below).
metrics::get().packets_sent.inc();
metrics::get().disconnects_total.inc(&["beacon_timeout"]);
metrics::get().tx_latency_us.observe(42);§Interrupt-context safety
Warning: metric access is not interrupt-safe on targets that have pointer-width atomic compare-and-swap but lack native 64-bit atomics.
On those targets, portable-atomic implements the u64, i64, and f64
storage used by metrics with global locks. thumbv7em-none-eabihf is one
affected target. If foreground code is preempted while it holds one of
those locks and an interrupt handler accesses the same metric — or another
metric mapped to the same fallback lock — the interrupt handler spins while
the foreground code cannot resume to release the lock, causing a deadlock.
The cs-atomics feature supplies atomic compare-and-swap through
critical-section on targets that lack it, such as
thumbv6m-none-eabi. It does not replace the global-lock 64-bit
fallback on targets such as thumbv7em-none-eabihf, which already have
pointer-width compare-and-swap. No embeprom feature currently removes
this restriction on those targets.
Until the storage implementation changes, do not access or render metrics
from an interrupt handler on an affected target when foreground code can
also access metrics. See the
portable-atomic fallback documentation
for the underlying implementation choices and their system-level safety
requirements.
§Registration
The get() accessor generated by metrics! (metrics::get() above)
self-registers its group with the global registry the first time it’s
called — via OnceRegister, a one-shot guard, so this costs one atomic
load on every call after registration completes. A caller concurrent with
the first registration may make a harmless deduplicated attempt of its
own. No explicit step is required in main(), but one is available when
the application wants eager registration or explicit capacity handling.
This means a metrics group that’s declared but never recorded stays
absent from scrapes until first touched (it isn’t visible at 0 from
boot the way an eagerly-registered metric would be). If a group’s first
recording happens to occur when the global registry is already at
capacity (see MAX_GROUPS), that group’s metrics are
silently dropped from future scrapes rather than panicking — logged once
per group via log::error! if the log feature is enabled.
To register a group eagerly instead (so it’s visible at 0 from boot),
or to make a full registry a hard startup failure rather than a silent
one, call register explicitly, e.g. in main():
embeprom::register(&metrics::METRICS).unwrap();Calling register for a group that already self-registered (or vice
versa) is safe: Registry::register dedups by static identity, so
a group is never counted twice.
A caller-owned registry can have any capacity and does not need to be
visible to the crates declaring metrics. The final application can
explicitly register their public METRICS statics and render its registry
directly:
mod dependency_metrics {
embeprom::metrics! {
/// Completed jobs.
jobs_completed: Counter,
}
}
static REGISTRY: embeprom::Registry<8> = embeprom::Registry::new();
REGISTRY.register(&dependency_metrics::METRICS).unwrap();
dependency_metrics::get().jobs_completed.inc();
let mut renderer = embeprom::Renderer::<8>::from_registry(®ISTRY);
assert!(renderer.next_line().unwrap().is_some());The same group may coexist in the global and caller-owned registries; each
registry deduplicates it independently. A declaration can instead use
metrics! { registry = PATH; ... } to lazily target a visible registry, or
metrics! { registration = manual; ... } to opt that group out of global
self-registration entirely.
§Exporting
Renderer is a pull-based cursor over every registered group’s
metrics, rendered into Prometheus text exposition format. It’s
deliberately synchronous and no_std so it has no opinion about how
bytes reach the network; the caller drives it, awaiting between lines as
needed:
let mut renderer = embeprom::Renderer::new();
while let Some(line) = renderer.next_line().unwrap() {
// send `line.as_bytes()` to whatever sink you have.
}Renderer::new snapshots the built-in global registry. Render a specific
caller-owned registry with Renderer::from_registry:
let registry = embeprom::Registry::<4>::new();
let mut renderer = embeprom::Renderer::<4>::from_registry(®istry);
assert_eq!(renderer.next_line(), Ok(None));The default renderer holds one line of at most MAX_LINE bytes. Select a
different bound with Renderer::with_line_capacity::<512>().
RenderError::LineTooLong reports the exact required capacity and is
returned once; the cursor skips that line, so the caller can report the
error and continue calling Renderer::next_line through the end of the
exposition. A histogram snapshot-capacity error similarly skips the
affected metric family.
When consistent-histograms is enabled, the renderer also holds reusable
scratch for MAX_HISTOGRAM_BUCKETS finite buckets. Tune both bounds with
Renderer::with_capacities::<LINE, HIST_BUCKETS>().
For a synchronous sink implementing core::fmt::Write, use
write_all instead.
§Serving over HTTP with picoserve
embeprom has no dependency on picoserve (or any HTTP server), but its
pull-based renderer is a direct match for picoserve’s chunked response
body: a Chunks implementation writes one rendered line per HTTP chunk
and awaits between lines.
use picoserve::response::chunked::{ChunkWriter, Chunks, ChunksWritten};
struct MetricsResponse;
impl Chunks for MetricsResponse {
fn content_type(&self) -> &'static str {
embeprom::CONTENT_TYPE
}
async fn write_chunks<W: picoserve::io::Write>(
self,
mut chunk_writer: ChunkWriter<W>,
) -> Result<ChunksWritten, W::Error> {
let mut renderer = embeprom::Renderer::new();
while let Some(line) = renderer
.next_line()
.expect("increase the Renderer line capacity")
{
chunk_writer.write_chunk(line.as_bytes()).await?;
}
chunk_writer.finalize().await
}
}
// route:
// picoserve::routing::get(|| async {
// picoserve::response::chunked::ChunkedResponse::new(MetricsResponse)
// })Content
(picoserve’s fixed-length response body trait) is deliberately not used
here: it requires knowing the total body length up front. A discarded
render pass cannot provide that guarantee because metrics and labeled
series can change before the response body is rendered.
§Labeled metrics and cardinality
CounterVec, GaugeVec, IntHistogramVec (and, with the float
feature, GaugeF64Vec and HistogramVec) each declare a maximum number of
distinct label-value combinations via a const generic (e.g. CounterVec<4>
for up to 4 series). Once that capacity is exhausted, newly observed label
combinations are silently routed to unrendered sink handles whose updates
are no-ops, while existing series keep updating normally. Oversized
rendered label blocks use the same sink behavior.
For stable label values, call with once during initialization and retain
its series handle. Updating that handle accesses the metric storage
directly, avoiding repeated label construction and label-map lookup. The
convenience methods that accept label values perform a lookup on every
call and are best reserved for dynamic or infrequent labels. Bound series
handles are readable the same way as the corresponding scalar types
(get on counters/gauges; bounds / bucket / count / sum on
histograms). Sink handles read as zero.
IntHistogram::series and IntHistogramVec::with both return
IntHistSeries (and the same for the float histogram types), so a
helper can take impl Into<IntHistSeries<'a>> and accept either an
unlabeled histogram or a bound labeled series.
Macros§
- metrics
- Declare a module-scoped metrics group: a
Metricsstruct with one field per metric, renderable viacrate::Renderer. The generatedget()accessor self-registers the group with the global registry on first call (seecrate::OnceRegister) — no separate registration step is needed, butcrate::registerremains available for eager registration.
Structs§
- Counter
- A Prometheus counter: a cumulative value that only increases (or resets to zero, e.g. on restart).
- Counter
Series - An infallible handle to one
CounterVecseries. - Counter
Vec - A labeled counter collection with at most
Ndistinct label-value combinations,Klabel names, and a rendered label-block byte budgetV. - Gauge
- A Prometheus gauge holding a signed integer value.
- Gauge
F64 - A Prometheus gauge holding a floating-point value.
- Gauge
F64Series - An infallible handle to one
GaugeF64Vecseries. - Gauge
F64Vec - A labeled
f64gauge collection with at mostNdistinct label-value combinations,Klabel names, and a rendered label-block byte budgetV. - Gauge
Series - An infallible handle to one
GaugeVecseries. - Gauge
Vec - A labeled gauge collection with at most
Ndistinct label-value combinations,Klabel names, and a rendered label-block byte budgetV. - Hist
Series - An infallible, reusable handle to one floating-point histogram series.
- Histogram
- A Prometheus histogram over
f64observations. SeeIntHistogramfor the storage and consistency model; preferIntHistogramwhen values are naturally integral, sincef64atomics have no native CAS on most Cortex-M cores. - Histogram
Snapshot - A coherent histogram reading backed by the initialized prefix of the caller-provided bucket buffer.
- Histogram
Snapshot Error - The caller-provided histogram snapshot buffer was too small.
- Histogram
Vec - A labeled histogram collection over
f64observations. SeeIntHistogramVecfor the storage/capacity model; prefer that type when values are naturally integral. - IntHist
Series - An infallible, reusable handle to one histogram series.
- IntHistogram
- A Prometheus histogram over
u64observations, withBfinite buckets plus an implicit+Infbucket (represented bycount). - IntHistogram
Vec - A labeled histogram collection over
u64observations, with at mostNdistinct label-value combinations,Bfinite buckets shared by all series,Klabel names, and a rendered label-block byte budgetV. - Once
Register - A one-shot guard that registers a metric group with the global registry
on the first call to
ensure, and does nothing on every subsequent call. Used by the accessor function generated bycrate::metrics!so that recording a metric for the first time self-registers its group, with no explicitmain()-side call needed. - Registry
- A fixed-capacity registry of metric groups, holding at most
Ngroups. - Registry
Full - Returned by
Registry::registerwhen the registry is already at capacityN. - Renderer
- A pull-based cursor over a snapshot of registered metric groups, producing Prometheus text-exposition-format output one complete line at a time, without requiring the whole output to fit in memory at once.
Enums§
- Render
Error - A failure while producing or writing Prometheus exposition text.
- Value
- A single Prometheus sample value.
Constants§
- CONTENT_
TYPE - The
Content-Typevalue for Prometheus text exposition format. - LABEL_
VALUE_ LEN - MAX_
GROUPS - MAX_
HISTOGRAM_ BUCKETS - Default number of finite histogram buckets that a renderer can snapshot
when
consistent-histogramsis enabled. This scratch capacity is reused for each scalar histogram or histogram-vector series and can be overridden withcrate::Renderer::with_capacities. - MAX_
LINE - Default maximum length in bytes of a single rendered output line. A line
exceeding this returns
crate::RenderError::LineTooLong. Override it for one renderer withcrate::Renderer::with_line_capacity.
Functions§
- register
- Register a metric group with the global registry.
- snapshot
- Copy out the groups currently registered with the global registry.
- valid_
label_ name - Whether
sis a valid Prometheus label name:[a-zA-Z_][a-zA-Z0-9_]*, and not prefixed with__(reserved for internal use). - valid_
metric_ name - Whether
sis a valid Prometheus metric name:[a-zA-Z_:][a-zA-Z0-9_:]*. An empty string (no namespace) is considered valid. - write_
all - Render the global registry’s metrics into
w. This is a convenience for synchronous sinks; asynchronous sinks can await betweenRenderer::next_linecalls.
Type Aliases§
- Group
Snapshot - A snapshot of the groups registered with a
Registryat a point in time.