Rust Tracing Basic Setup – Andy Balaam Blog


March 29, 2025 [Programming, Programming Languages, Rust, Tech]

I spent yesterday’s age trying to find ways to use the Rust search library (and tracking tracking) for the case of very simple logging use.

I want to use tracing Because a) quickly becomes the standard everywhere and b) I use a library that uses it.

I find it very difficult to find a simple example that takes his log level from RUST_LOG environmental variables, or use non-sepele default. This is what I produce:

$ cargo add tracing
$ cargo add tracing-subscriber --features env-filter
use tracing_subscriber::FmtSubscriber;

fn main() {
    const DEFAULT_LOGGING: &str = "myprogram=info,warn";

    let rust_log = std::env::var("RUST_LOG")
        .ok()
        .and_then(|s| if s.is_empty() { None } else { Some(s) })
        .unwrap_or_else(|| DEFAULT_LOGGING.to_owned());

    tracing::subscriber::set_global_default(
        FmtSubscriber::builder().with_env_filter(rust_log).finish(),
    )
    .expect("tracing setup failed");

    // The rest of my program here ...
}

That myprogram=info,warn The section set my project log level info and whatever library I use warn. You have to replace myprogram with the name of your project.

This sets the default logging level that can be overwritten by launching a program with EG RUST_LOG=debug ./myprogram To set the level to debug
everywhere or eg RUST_LOG="myproject=debug,warn" ./myprogram to do something smarter.

(Format of the list of directions separated by this coma is documented in tracing_fmt :: builder :: with_env_filter and envfilter.)

When finished, I can record using a code like this:

use tracing::{debug, info};

pub fn myfun() {
    let x = 3;
    info!("The number is {x}");
    debug!("DEBUG ONLY");
}

If anyone knows a simpler way to achieve this result, tell me. I spent a long time EnvFilter::with_default_directive And similar things before I decided to check the contents RUST_LOG Manually if I want a more complex default (not a single direction).

Side note: wow, tracing_subscriber Difficult to use! I could not find a simple example – the link was welcomed.



Game Online

Gaming Hub