Opentelemetry with async code

I have an app that's built around tokio and has async code everywhere. Now I'm trying to instrument the app and add opentelemetry support - opentelemetry - crates.io: Rust Package Registry.

Sample form opentelemetry crate's README.

use opentelemetry::{global, sdk::export::trace::stdout, trace::Tracer};

fn main() {
    // Create a new trace pipeline that prints to stdout
    let tracer = stdout::new_pipeline().install_simple();

    tracer.in_span("doing_work", |cx| {
        // Traced app logic here...
    });

    // Shutdown trace pipeline
    global::shutdown_tracer_provider();
}

It looks like tracer.in_span(...) takes a closure, and Rust async closures haven't been stabilized yet. So I'm not very sure how to proceed.

You should probably be using the tracing-opentelemetry crate.

Regarding async closures, I think it is a misnomer to talk about the non-stabilized variant. Closures that return async blocks work very well today and are more-or-less the same as what the unstable async closures would provide.

1 Like

To clarify @alice: || async {} instead of async || {}. There's also move || async move {}, but I vaguely remember there's some annoying quirks there.

1 Like