console icon indicating copy to clipboard operation
console copied to clipboard

Tasks spawned by #[tokio::main] are not captured

Open zaharidichev opened this issue 3 years ago • 6 comments

Since a usual pattern is to call console_subscriber::init() at the beginning of the main function, we end up initializing the subscriber after the task spawned by the tokio macro is created. We then end up in a situation where we cannot associate tracing events with any task. The result of that is printing a bunch of error messages to the console.

Related: https://github.com/tokio-rs/tokio/issues/4206

zaharidichev avatar Nov 22 '21 20:11 zaharidichev

I guess one way to avoid that is to export a macro from the console that will function in a similar way to tokio::main but will init the subscriber before the task is spawned.

zaharidichev avatar Nov 22 '21 20:11 zaharidichev

ahhh, good catch...that makes sense! hmm. this is a problem that's kind of endemic with the #[tokio::main] macro; I've also seen people confused when an #[instrument] attribute on main doesn't do anything. it would be nice to have a solution for this, but just ignoring them is fine for now...

hawkw avatar Nov 22 '21 20:11 hawkw

Is there a workaround for that?

hellow554 avatar Feb 14 '22 15:02 hellow554

Is there a workaround for that?

Rather than using #[tokio::main], use Tokio's Runtime::new() API, and ensure that console_subscriber::init() is called before creating the Tokio runtime.

For example, if you are currently writing something like this:

#[tokio::main]
async fn main() {
    console_subscriber::init();
    // actually do stuff
}

you could instead write

fn main() {
    console_subscriber::init();
    let rt = tokio::runtime::Runtime::new()
        .expect("tokio runtime should be created successfully");

    rt.block_on(async move {
        // actually do stuff
    });
}

This should get you the same runtime configuration as using #[tokio::main], but here, the console will be set up before the block_on method is called.

hawkw avatar Feb 14 '22 20:02 hawkw

What about something like #[tokio::main(tracing)] or

#[tracing]
#[tokio::main]
async fn main { }

?

hellow554 avatar Feb 14 '22 20:02 hellow554