Tracing Configuration Snippet

This configuration accomplishes the following:

  • If RUST_LOG environment variable is present, use that
  • If RUST_LOG is not present, default to the provided verbosity level

You'll need these crates:

# Cargo.toml

[dependencies]
tracing = "0.1.41"
tracing-subscriber = { version = "0.3.20", features = ["env-filter"] }

[dependencies.clap-verbosity-flag]
version = "3.0.4"
default-features = false
features = ["tracing"]

Then in your clap "args" struct you'll add the Verbosity type:

use clap_verbosity_flag::{Verbosity, WarnLevel};

#[derive(Parser, Debug)]
pub struct Args {
    #[command(flatten)]
    pub verbosity: Verbosity<WarnLevel>,
}

Omitting the level type will cause Verbosity to default to the "error" level.

Finally, you can initialize the subscriber:

use clap_verbosity_flag::{Verbosity, WarnLevel};
use std::env;
use tracing_subscriber::EnvFilter;
use tracing_subscriber::{Layer, layer::SubscriberExt, util::SubscriberInitExt};

pub fn init_tracing(verbosity: Verbosity<WarnLevel>) {
    let filter = match env::var("RUST_LOG") {
        // Use RUST_LOG if found
        Ok(filter_str) => filter_str,
        // Otherwise use this fallback
        Err(_) => format!("YOUR_CRATE_NAME_HERE={verbosity}"),
    };

    tracing_subscriber::registry()
        .with(tracing_subscriber::fmt::layer().with_filter(EnvFilter::new(filter)))
        .init();
}

Remember to change YOUR_CRATE_NAME_HERE to include all crates (comma-delimited) where you want tracing enabled.

Comments