tokio-rs / tracing

Application level tracing for Rust.
https://tracing.rs
MIT License
5.33k stars 697 forks source link

Cannot activate `tracing-subscriber/tracing-log` feature for pretty log formatting when manually registering global logger #2817

Open Nemo157 opened 9 months ago

Nemo157 commented 9 months ago

Bug Report

Version

tracing-attributes v0.1.27 (proc-macro)
tracing-core v0.1.32
tracing-log v0.2.0
tracing-serde v0.1.3
tracing-subscriber v0.3.18
tracing v0.1.40

Crates

tracing-subscriber

Description

We are registering a custom global log logger which forwards to tracing-log. If we try activating the tracing-subscriber/tracing-log feature to get nicer rendering of these logs then that fails with

thread 'main' panicked at /root/.cargo/registry/src/index.crates.io-6f17d22bba15001f/tracing-subscriber-0.3.18/src/util.rs:91:14:
failed to set global default subscriber: SetLoggerError(())

It seems like there should be a way to disable this registration through the SubscriberBuilder.

davidbarsky commented 9 months ago

Sorry, it took me a second to understand what was happening, but I can see how SubscriberInitExt::{init, try_init} is problematic in your case. I'm not entirely sure how we should address this issue in SubscriberInitExt (in that the goal of SubscriberInitExt is to be a simple convenience wrapper), but you can unblock https://github.com/rust-lang/docs.rs/issues/2336 by writing tracing_subscriber::subscriber::set_global_default with the composed layers/registry.

I am also guessing that you're initializing each a subscriber in each branch because the layer/subscriber types can get a bit gnarly—fair enough. What might help you is that Option<Layer> is also a Layer (see this documentation), which means that you can check for the presence of the SENTRY_DSN variable and add a Some(sentry_layer) or None to the registry as needed. You shouldn't need to check for any initialization errors if you take that approach.