Skip to main content

defect_obs/
tracing_init.rs

1//! tracing-subscriber initialization.
2//!
3//! Process-level — must be called only once. `RUST_LOG` takes precedence over the config
4//! file's `[tracing].filter`.
5
6use tracing_subscriber::EnvFilter;
7
8const DEFAULT_FILTER: &str = "info,toac=warn";
9
10/// Initializes the global tracing subscriber.
11///
12/// Resolution order: `RUST_LOG` env > argument `filter` > `DEFAULT_FILTER`.
13/// Output goes to stderr. When `jsonl` is true, each log record is emitted as one JSON
14/// line (JSONL/NDJSON); otherwise human-readable text with ANSI colors auto-enabled when
15/// stderr is a terminal.
16pub fn init_tracing(filter: Option<&str>, jsonl: bool) -> anyhow::Result<()> {
17    let default_filter = filter.unwrap_or(DEFAULT_FILTER);
18    let env_filter =
19        EnvFilter::try_from_default_env().unwrap_or_else(|_| EnvFilter::new(default_filter));
20    let builder = tracing_subscriber::fmt()
21        .with_env_filter(env_filter)
22        .with_writer(std::io::stderr)
23        .with_target(true);
24    if jsonl {
25        builder
26            .json()
27            .try_init()
28            .map_err(|e| anyhow::anyhow!("tracing init failed: {e}"))
29    } else {
30        builder
31            .with_ansi(std::io::IsTerminal::is_terminal(&std::io::stderr()))
32            .try_init()
33            .map_err(|e| anyhow::anyhow!("tracing init failed: {e}"))
34    }
35}