loggingrustrust-tracing

tracing use RUST_LOG env var and ignore other crates


I have a binary application (with the functionality broken out into a lib.rs) for which I am trying to set up tracing. The behaviour I am trying to achieve is:

I believe that a combination of:

tracing_subscriber::fmt()
    .with_env_filter(EnvFilter::new("my_crate"))
    .init();

and

tracing_subscriber::fmt()
    .with_env_filter(EnvFilter::from_default_env())
    .init();

Should achieve what I am looking for, but I can't work out how to combine these. I tried the below but that didn't work.

tracing_subscriber::fmt()
    .with_env_filter(
        EnvFilter::from_default_env()
            .add_directive(Directive::from_str("my_crate").unwrap()),
    )
    .init();

Solution

  • Simple is better than complex:

    if let Ok(level) = std::env::var("RUST_LOG") {
        tracing_subscriber::fmt()
            .with_env_filter(EnvFilter::new(&format!("my_crate={level}")))
            .init();
    }
    

    You know what, let's be a bit more future-proof against future crate name change:

    if let Ok(level) = std::env::var("RUST_LOG") {
        tracing_subscriber::fmt()
            .with_env_filter(EnvFilter::new(&format!(
                "{}={level}",
                env!("CARGO_PKG_NAME").replace("-", "_"),
            )))
            .init();
    }