foundations icon indicating copy to clipboard operation
foundations copied to clipboard

API for automatically tracking duration of trace spans in a metric

Open evanrittenhouse opened this issue 5 months ago • 1 comments

A very common use case for traces is understanding how long specific functions take. It'd be interesting if we could make that queryable for more fine-grained visibility into how services behave. I propose an API that requires both the tracing and metrics features which could be used to automatically do this.

Doing this right now would entail something like this:

#[tracing(span_fn = "do_something")]
async fn do_something() {
    let _guard = do_something_duration.start_timer();
    ...
    // _guard drops and records the duration
}

Instead, we could do something like this:

#[tracing(span_fn = "do_something", track_duration_with = "do_something_duration")]
async fn do_something() {
    // HistogramTimer is attached to the SpanScope, automatically recording how long `do_something` took
}

We'd have to provide a fully-qualified metric name, similar to how the crate_path works, to pick the metric up properly. The metric would have to be created as normal - we could panic or something if it doesn't exist. I think we could just add the guard onto SpanScope and attach it when call wrap_with_span in the macro parsing code.

This could be more generalized to something like

tracing::span("do_something").track_duration_with("do_something_duration").apply(...)

Happy to raise a PR if this is something we want to do, curious what people think

evanrittenhouse avatar Jun 30 '25 23:06 evanrittenhouse

I really like it

rushilmehra avatar Jul 04 '25 03:07 rushilmehra