Expand description
Monitor key metrics of tokio tasks and runtimes.
§Monitoring task metrics
Monitor key metrics of tokio tasks.
In the below example, a TaskMonitor
is constructed and used to
instrument three worker tasks; meanwhile, a fourth task
prints metrics in 500ms intervals:
use std::time::Duration;
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
// construct a metrics taskmonitor
let metrics_monitor = tokio_metrics::TaskMonitor::new();
// print task metrics every 500ms
{
let metrics_monitor = metrics_monitor.clone();
tokio::spawn(async move {
for interval in metrics_monitor.intervals() {
// pretty-print the metric interval
println!("{:?}", interval);
// wait 500ms
tokio::time::sleep(Duration::from_millis(500)).await;
}
});
}
// instrument some tasks and await them
// note that the same taskmonitor can be used for multiple tasks
tokio::join![
metrics_monitor.instrument(do_work()),
metrics_monitor.instrument(do_work()),
metrics_monitor.instrument(do_work())
];
Ok(())
}
async fn do_work() {
for _ in 0..25 {
tokio::task::yield_now().await;
tokio::time::sleep(Duration::from_millis(100)).await;
}
}
§Monitoring runtime metrics (unstable)
Monitor key metrics of a tokio runtime.
This functionality requires tokio_unstable
and the crate feature rt
.
In the below example, a RuntimeMonitor
is constructed and
three tasks are spawned and awaited; meanwhile, a fourth task prints metrics
in 500ms intervals:
use std::time::Duration;
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
let handle = tokio::runtime::Handle::current();
// construct the runtime metrics monitor
let runtime_monitor = tokio_metrics::RuntimeMonitor::new(&handle);
// print runtime metrics every 500ms
{
tokio::spawn(async move {
for interval in runtime_monitor.intervals() {
// pretty-print the metric interval
println!("{:?}", interval);
// wait 500ms
tokio::time::sleep(Duration::from_millis(500)).await;
}
});
}
// await some tasks
tokio::join![
do_work(),
do_work(),
do_work(),
];
Ok(())
}
async fn do_work() {
for _ in 0..25 {
tokio::task::yield_now().await;
tokio::time::sleep(Duration::from_millis(100)).await;
}
}
Structs§
- Instrumented
- An async task that has been instrumented with
TaskMonitor::instrument
. - Runtime
Intervals tokio_unstable
andrt
- Iterator returned by
RuntimeMonitor::intervals
. - Runtime
Metrics tokio_unstable
andrt
- Key runtime metrics.
- Runtime
Monitor tokio_unstable
andrt
- Monitors key metrics of the tokio runtime.
- Task
Metrics - Key metrics of instrumented tasks.
- Task
Monitor - Monitors key metrics of instrumented tasks.