Expand description
Metrics handling library based on the prometheus-client crate.
§Overview
- The crate supports defining common metric types (
Counters,Gauges andHistograms). A single metric is represented by an instance of these types; it can be reported using methods likeCounter::inc(),Gauge::set()orHistogram::observe(). - Metrics can be grouped into a
Family. Essentially, aFamilyis a map in which metrics are values keyed by a set of labels. SeeEncodeLabelValueandEncodeLabelSetderive macros for more info on labels. - To define metrics, a group of logically related metrics is grouped into a struct
and the
Metricstrait is derived for it. This resolves full metric names and records additional metadata, such as help (from doc comments), unit of measurement andBucketsfor histograms. - Metric groups are registered in a
Registry, which then allows to encode metric data in the OpenMetrics text format. Registration can be automated using theregisterattribute, but it can be manual as well. - In order to allow for metrics computed during scraping, you can use
Collector. - To share one or more labels for a group of metrics, wrap them in a
MetricsFamily.
§Examples
§Defining metrics
use vise::*;
use std::{fmt, time::Duration};
/// Metrics defined by the library or application. A single app / lib can define
/// multiple metric structs.
#[derive(Debug, Clone, Metrics)]
#[metrics(prefix = "my_app")]
// ^ Prefix added to all field names to get the final metric name (e.g., `my_app_latencies`).
pub(crate) struct MyMetrics {
/// Simple counter. Doc comments for the fields will be reported
/// as Prometheus metric descriptions.
pub counter: Counter,
/// Integer-valued gauge. Unit will be reported to Prometheus and will influence metric name
/// by adding the corresponding suffix to it (in this case, `_bytes`).
#[metrics(unit = Unit::Bytes)]
pub gauge: Gauge<u64>,
/// Group of histograms with the "method" label (see the definition below).
/// Each `Histogram` or `Family` of `Histogram`s must define buckets; in this case,
/// we use default buckets for latencies.
#[metrics(buckets = Buckets::LATENCIES)]
pub latencies: Family<Method, Histogram<Duration>>,
}
/// Isolated metric label. Note the `label` name specification below.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, EncodeLabelSet, EncodeLabelValue)]
#[metrics(label = "method")]
pub(crate) struct Method(pub &'static str);
// For the isolated metric label to work, you should implement `Display` for it:
impl fmt::Display for Method {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(formatter, "{}", self.0)
}
}§Registering metrics automatically
Commonly, metrics can be registered by defining a static:
#[derive(Debug, Clone, Metrics)]
pub(crate) struct MyMetrics {
// defined in a previous code sample
}
#[vise::register]
pub(crate) static MY_METRICS: Global<MyMetrics> = Global::new();
// All registered metrics can be collected in a `Registry`:
let registry: Registry = MetricsCollection::default().collect();
// Do something with the `registry`, e.g. create an exporter.
fn metered_logic() {
// method logic...
MY_METRICS.gauge.set(42);
}§Registering metrics manually
It is possible to add metrics manually to a Registry. As a downside, this approach requires
boilerplate to register all necessary metrics in an app and potentially libraries
that it depends on.
#[derive(Debug, Clone, Metrics)]
pub(crate) struct MyMetrics {
// defined in a previous code sample
}
let mut registry = Registry::empty();
let my_metrics = MyMetrics::default();
registry.register_metrics(&my_metrics);
// Do something with the `registry`, e.g. create an exporter.
// After registration, metrics can be moved to logic that reports the metrics.
// Note that metric types trivially implement `Clone` to allow sharing
// them among multiple components.
fn metered_logic(metrics: MyMetrics) {
// method logic...
metrics.gauge.set(42);
}
metered_logic(my_metrics);Modules§
- descriptors
- Metric descriptors.
- traits
- Traits used for metric definitions, such as
GaugeValueandHistogramValue.
Structs§
- Before
Scrape Error - Error that can occur when calling
Collector::before_scrape(). - Buckets
- Buckets configuration for a
Histogramor aFamilyof histograms. - Collector
- Collector allowing to define metrics dynamically.
- Counter
- Open Metrics
Counterto measure discrete events. - Duration
AsSecs - Wraps a
Durationso that it can be used as a label value, which will be set to the fractional number of seconds in the duration, i.e.Duration::as_secs_f64(). Mostly useful forInfometrics. - Family
- Family of metrics labelled by one or more labels.
- Gauge
- Gauge metric.
- Gauge
Guard - Guard for a
Gaugereturned byGauge::inc_guard(). When dropped, a guard decrements the gauge by the same value that it was increased by when creating the guard. - Global
- Global instance of
Metricsallowing to access contained metrics from anywhere in code. Should be used as astaticitem. - Histogram
- Histogram metric.
- Info
- Information metric.
- Latency
Observer - Observer of latency for a
Histogram. - Lazy
Item - Lazily accessed member of a
FamilyorMetricsFamily. Returned byget_lazy()methods. - Metric
Builder - Builder of a single metric or a
Familyof metrics. Parameterized by buckets (only applicable toHistograms and their families) and labels (only applicable to families). - Metrics
Collection - Configures collection of
registered metrics. - Metrics
Family - Family of
Metrics. Allows applying one or more labels for all contained metrics, as if each of them was enclosed in aFamily. - Registered
Descriptors - Descriptors of all metrics in a registry.
- Registry
- Metrics registry.
- SetInfo
Error - Error returned from
Info::set().
Enums§
Traits§
- Build
Metric - Metric that can be constructed from a
MetricBuilder. - Collect
ToRegistry - Collects metrics from this type to registry. This is used by the
registermacro to handle registration ofGlobalmetrics andCollectors. - Metrics
- Collection of metrics for a library or application. Should be derived using the corresponding macro.
- Metrics
Visitor - Visitor for
Metrics.
Type Aliases§
- Labeled
Family Familywith separately specified label names.
Attribute Macros§
- register
- Registers a
Globalmetrics instance orCollector, so that it will be included into registries instantiated usingMetricsCollection.
Derive Macros§
- Encode
Label Set - Derives the
EncodeLabelSettrait for a type, which encodes a set of metric labels. - Encode
Label Value - Derives the
EncodeLabelValuetrait for a type, which encodes a metric label value. - Metrics
- Derives the
Metricstrait for a type.