Crate vise

Source
Expand description

Metrics handling library based on the prometheus-client crate.

§Overview

  • The crate supports defining common metric types (Counters, Gauges and Histograms). A single metric is represented by an instance of these types; it can be reported using methods like Counter::inc(), Gauge::set() or Histogram::observe().
  • Metrics can be grouped into a Family. Essentially, a Family is a map in which metrics are values keyed by a set of labels. See EncodeLabelValue and EncodeLabelSet derive macros for more info on labels.
  • To define metrics, a group of logically related metrics is grouped into a struct and the Metrics trait is derived for it. This resolves full metric names and records additional metadata, such as help (from doc comments), unit of measurement and Buckets for 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 the register attribute, 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 GaugeValue and HistogramValue.

Structs§

BeforeScrapeError
Error that can occur when calling Collector::before_scrape().
Buckets
Buckets configuration for a Histogram or a Family of histograms.
Collector
Collector allowing to define metrics dynamically.
Counter
Open Metrics Counter to measure discrete events.
DurationAsSecs
Wraps a Duration so 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 for Info metrics.
Family
Family of metrics labelled by one or more labels.
Gauge
Gauge metric.
GaugeGuard
Guard for a Gauge returned by Gauge::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 Metrics allowing to access contained metrics from anywhere in code. Should be used as a static item.
Histogram
Histogram metric.
Info
Information metric.
LatencyObserver
Observer of latency for a Histogram.
LazyItem
Lazily accessed member of a Family or MetricsFamily. Returned by get_lazy() methods.
MetricBuilder
Builder of a single metric or a Family of metrics. Parameterized by buckets (only applicable to Histograms and their families) and labels (only applicable to families).
MetricsCollection
Configures collection of registered metrics.
MetricsFamily
Family of Metrics. Allows applying one or more labels for all contained metrics, as if each of them was enclosed in a Family.
RegisteredDescriptors
Descriptors of all metrics in a registry.
Registry
Metrics registry.
SetInfoError
Error returned from Info::set().

Enums§

Format
Metrics export format.
Unit
Metric units recommended by Open Metrics.

Traits§

BuildMetric
Metric that can be constructed from a MetricBuilder.
CollectToRegistry
Collects metrics from this type to registry. This is used by the register macro to handle registration of Global metrics and Collectors.
Metrics
Collection of metrics for a library or application. Should be derived using the corresponding macro.
MetricsVisitor
Visitor for Metrics.

Type Aliases§

LabeledFamily
Family with separately specified label names.

Attribute Macros§

register
Registers a Global metrics instance or Collector, so that it will be included into registries instantiated using MetricsCollection.

Derive Macros§

EncodeLabelSet
Derives the EncodeLabelSet trait for a type, which encodes a set of metric labels.
EncodeLabelValue
Derives the EncodeLabelValue trait for a type, which encodes a metric label value.
Metrics
Derives the Metrics trait for a type.