Skip to main content

spec_driven_docs/
logging.rs

1//! tracing-subscriber installation. Called once from `main`.
2//!
3//! Honors `RUST_LOG` when set; otherwise derives a directive from the
4//! `-v`/`-vv`/`-vvv` flag count. Diagnostics go to stderr so stdout stays
5//! reserved for command output. No other module installs a subscriber.
6
7use tracing_subscriber::layer::SubscriberExt;
8use tracing_subscriber::util::SubscriberInitExt;
9use tracing_subscriber::{EnvFilter, fmt};
10
11/// Install the process-wide subscriber.
12///
13/// # Errors
14///
15/// Fails when a subscriber is already installed.
16pub fn init(verbosity: u8) -> anyhow::Result<()> {
17    let default_directive = match verbosity {
18        0 => "warn",
19        1 => "info",
20        2 => "debug",
21        _ => "trace",
22    };
23    let filter =
24        EnvFilter::try_from_default_env().unwrap_or_else(|_| EnvFilter::new(default_directive));
25
26    tracing_subscriber::registry()
27        .with(filter)
28        .with(fmt::layer().with_writer(std::io::stderr).with_target(false))
29        .try_init()
30        .map_err(|e| anyhow::anyhow!("install tracing subscriber: {e}"))
31}