tokio-rs / tokio-metrics

Utilities for collecting metrics from a Tokio application

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Emit task metrics for single invocations instead of interval samples

declanvk opened this issue · comments

Hello,

This is a feature request for some way to get the TaskMetrics for the invocation of a single future. Something like:

let monitor = tokio_metrics::TaskMonitor::new();

let (metrics, other_return_value) = monitor.instrument_single(some_future()).await;

The API usage above is not intended to be the actual API, just illustrating the idea. I want this feature is so that I can record metrics for the overhead every single execution of the some_future() future.

The ultimate reason is that I'm trying to write a program that measures the latency of remote service calls, and I want to understand what kind of overhead I'm seeing as a result of using an async runtime, as opposed to a simple blocking thread application. I'd like to see this on a per-request basis so that I can confirm that requests with high latency are only the result of the remote system, not a result of a delay in scheduling the task.

The metrics library is not really the place for this. I recommend you check out the tracing crate.

Hi @declanvk, does this function satisfy your use case?

pub async fn with_metrics<F>(future: F) -> (tokio_metrics::TaskMetrics, F::Output)
where
    F: std::future::Future
{
    let monitor = tokio_metrics::TaskMonitor::new();
    let future = monitor.instrument(future);
    let result = future.await;
    let metrics = monitor.cumulative();
    (metrics, result)
}

You can use it like:

let (metrics, other_return_value) = with_metrics(some_future()).await;

Thanks @jswrenn , I think that works perfectly! I'm a little concerned about the Arc overhead per new TaskMonitor, but I think it should be acceptable. Thanks again!