Struct RuntimeMetricsReporterBuilder

Source
pub struct RuntimeMetricsReporterBuilder { /* private fields */ }
Available on crate features rt and metrics-rs-integration only.
Expand description

A builder for the a RuntimeMetricsReporter that wraps the RuntimeMonitor, periodically reporting RuntimeMetrics to any configured metrics-rs recorder.

§Published Metrics

The published metrics are the fields of RuntimeMetrics, but with the tokio_ prefix added, for example, tokio_workers_count. If desired, you can use the with_metrics_transformer function to customize the metric names.

§Usage

To upload metrics via metrics-rs, you need to set up a reporter, which is actually what exports the metrics outside of the program. You must set up the reporter before you call describe_and_run.

You can find exporters within the metrics-rs docs. One such reporter is the metrics_exporter_prometheus reporter, which makes metrics visible through Prometheus.

You can use it for exampleto export Prometheus metrics by listening on a local Unix socket called prometheus.sock, which you can access for debugging by curl --unix-socket prometheus.sock localhost, as follows:

use std::time::Duration;

#[tokio::main]
async fn main() {
    metrics_exporter_prometheus::PrometheusBuilder::new()
        .with_http_uds_listener("prometheus.sock")
        .install()
        .unwrap();
    tokio::task::spawn(
        tokio_metrics::RuntimeMetricsReporterBuilder::default()
            // the default metric sampling interval is 30 seconds, which is
            // too long for quick tests, so have it be 1 second.
            .with_interval(std::time::Duration::from_secs(1))
            .describe_and_run(),
    );
    // Run some code
    tokio::task::spawn(async move {
        for _ in 0..1000 {
            tokio::time::sleep(Duration::from_millis(10)).await;
        }
    })
    .await
    .unwrap();
}

Implementations§

Source§

impl RuntimeMetricsReporterBuilder

Source

pub fn with_interval(self, interval: Duration) -> Self

Set the metric sampling interval, default: 30 seconds.

Note that this is the interval on which metrics are sampled from the Tokio runtime and then set on the metrics-rs reporter. Uploading the metrics upstream is controlled by the reporter set up in the application, and is normally controlled by a different period.

For example, if metrics are exported via Prometheus, that normally operates at a pull-based fashion, and the actual collection period is controlled by the Prometheus server, which periodically polls the application’s Prometheus exporter to get the latest value of the metrics.

Source

pub fn with_metrics_transformer( self, transformer: impl FnMut(&'static str) -> Key + Send + 'static, ) -> Self

Set a custom “metrics transformer”, which is used during build to transform the metric names into metric keys, for example to add dimensions. The string metric names used by this reporter all start with tokio_. The default transformer is just metrics::Key::from_static_name

For example, to attach a dimension named “application” with value “my_app”, and to replace tokio_ with my_app_


#[tokio::main]
async fn main() {
    metrics_exporter_prometheus::PrometheusBuilder::new()
        .with_http_uds_listener("prometheus.sock")
        .install()
        .unwrap();
    tokio::task::spawn(
        tokio_metrics::RuntimeMetricsReporterBuilder::default().with_metrics_transformer(|name| {
            let name = name.replacen("tokio_", "my_app_", 1);
            Key::from_parts(name, &[("application", "my_app")])
        })
        .describe_and_run()
    );
}
Source

pub fn build(self) -> RuntimeMetricsReporter

Build the RuntimeMetricsReporter for the current Tokio runtime. This function will capture the Counters, Gauges and Histograms from the current metrics-rs reporter, so if you are using with_local_recorder, you should wrap this function and describe with it.

For example:


#[tokio::main]
async fn main() {
    let builder = tokio_metrics::RuntimeMetricsReporterBuilder::default();
    let recorder = Arc::new(metrics_util::debugging::DebuggingRecorder::new());
    let metrics_reporter = metrics::with_local_recorder(&recorder, || builder.describe().build());

    // no need to wrap `run()`, since the metrics are already captured
    tokio::task::spawn(metrics_reporter.run());
}
Source

pub fn build_with_monitor( self, monitor: RuntimeMonitor, ) -> RuntimeMetricsReporter

Build the RuntimeMetricsReporter with a specific RuntimeMonitor. This function will capture the Counters, Gauges and Histograms from the current metrics-rs reporter, so if you are using with_local_recorder, you should wrap this function and describe with it.

Source

pub fn describe(self) -> Self

Call describe_counter etc. to describe the emitted metrics.

Describing metrics makes the reporter attach descriptions and units to them, which makes them easier to use. However, some reporters don’t support describing the same metric name more than once, so it is generally a good idea to only call this function once per metric reporter.

Source

pub async fn describe_and_run(self)

Runs the reporter (within the returned future), describing the metrics beforehand.

Describing metrics makes the reporter attach descriptions and units to them, which makes them easier to use. However, some reporters don’t support describing the same metric name more than once. If you are emitting multiple metrics via a single reporter, try to call describe once and run for each runtime metrics reporter.

§Working with a custom reporter

If you want to set a local metrics reporter, you shouldn’t be calling this method, but you should instead call .describe().build() within with_local_recorder and then call run (see the docs on build).

Source

pub async fn run_without_describing(self)

Runs the reporter (within the returned future), not describing the metrics beforehand.

§Working with a custom reporter

If you want to set a local metrics reporter, you shouldn’t be calling this method, but you should instead call .describe().build() within with_local_recorder and then call run (see the docs on build).

Trait Implementations§

Source§

impl Debug for RuntimeMetricsReporterBuilder

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Default for RuntimeMetricsReporterBuilder

Source§

fn default() -> Self

Returns the “default value” for a type. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.