Tokio metrics collector for Prometheus

tokio-metrics-collector on GitHub Action codecov tokio-metrics-collector on crates.io tokio-metrics-collector on docs.rs

Provides utilities for collecting Prometheus-compatible metrics from Tokio runtime and tasks.

toml [dependencies] tokio-metrics-collector = { version = "0.1.0" }

Documentation:

QuickStart

```Rust use prometheus::Encoder;

[tokio::main]

async fn main() { // register global runtime collector prometheus::defaultregistry() .register(Box::new( tokiometricscollector::defaultruntime_collector(), )) .unwrap();

// register global task collector
let task_collector = tokio_metrics_collector::default_task_collector();
prometheus::default_registry()
    .register(Box::new(task_collector))
    .unwrap();

// construct a TaskMonitor
let monitor = tokio_metrics_collector::TaskMonitor::new();
// add this monitor to task collector with label 'simple_task'
task_collector.add("simple_task", monitor.clone());

// spawn a background task and instrument
tokio::spawn(monitor.instrument(async {
    loop {
        // do something
        tokio::time::sleep(tokio::time::Duration::from_millis(500)).await;
    }
}));

// print metrics every tick
for _ in 0..5 {
    tokio::time::sleep(tokio::time::Duration::from_secs(1)).await;

    let encoder = prometheus::TextEncoder::new();
    let mut buffer = Vec::new();
    encoder
        .encode(&prometheus::default_registry().gather(), &mut buffer)
        .unwrap();
    let data = String::from_utf8(buffer.clone()).unwrap();

    println!("{}", data);
}

} ```

And a http server example, you can find in examples/server.rs.

Runtime Metrics

This unstable functionality requires tokio_unstable, and the rt crate feature. To enable tokio_unstable, the --cfg tokio_unstable must be passed to rustc when compiling. You can do this by setting the RUSTFLAGS environment variable before compiling your application; e.g.:

sh RUSTFLAGS="--cfg tokio_unstable" cargo build

Or, by creating the file .cargo/config.toml in the root directory of your crate. If you're using a workspace, put this file in the root directory of your workspace instead.

toml [build] rustflags = ["--cfg", "tokio_unstable"] rustdocflags = ["--cfg", "tokio_unstable"]

Task Metrics

License

tokio-metrics-collector is distributed under the terms of both the MIT license and the Apache License (Version 2.0).

See LICENSE-APACHE and LICENSE-MIT, and COPYRIGHT for details.