tracing use RUST_LOG env var and ignore other crates

132 views Asked by At

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:

  • Log events to stdout.
  • Events from anywhere that is not my crate should always be ignored.
  • Nothing should be logged if RUST_LOG is not set, otherwise only log to the level set by RUST_LOG.

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();
1

There are 1 answers

0
Chayim Friedman On BEST ANSWER

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();
}