crates/knut-tracing/src/lib.rs
//! # knut-tracing
//!
//! The one shared **tracing-subscriber bootstrap** for knut's binaries.
//!
//! `bifröst` and `knutpipe` both install the exact same subscriber — JSON lines
//! or pretty text, level from `RUST_LOG` (default `info`) — so a test or bencher
//! can drive either binary and assert on its structured events. That bootstrap
//! lived **byte-identically** in each binary's `main`; it lives ONCE here and
//! both consume it (REUSE — one copy, not a twin per binary).
//!
//! This is deliberately dependency-light (only `tracing-subscriber`): a binary
//! that just wants the shared logging bootstrap pulls nothing heavy along.
use tracing_subscriber::{EnvFilter, fmt};
/// Install a tracing subscriber: JSON lines or pretty text, level from
/// `RUST_LOG` (default `info`).
///
/// With `json` the subscriber emits one JSON object per log line
/// (machine-readable, current-span omitted); otherwise pretty text with the
/// event target. Installs the process-global default, so call it exactly once
/// at startup.
pub fn init_tracing(json: bool) {
let filter = EnvFilter::try_from_default_env().unwrap_or_else(|_| EnvFilter::new("info"));
if json {
fmt()
.with_env_filter(filter)
.json()
.with_current_span(false)
.init();
} else {
fmt().with_env_filter(filter).with_target(true).init();
}
}
#[cfg(test)]
mod tests {
use super::init_tracing;
/// Red-when-broken: the shared bootstrap must actually install a
/// process-global subscriber. We install it, then prove one is present by
/// showing a *second* install is rejected by the global-default guard. If
/// `init_tracing` regresses (bad filter build, wrong builder chain, or it
/// stops calling `.init()`) the second install would succeed and this fails.
/// Both binaries route `main` through this one call, so this pins the shared
/// contract. Only test in this crate that touches the global subscriber, so
/// there is no double-init race.
#[test]
fn init_tracing_installs_global_subscriber() {
init_tracing(false);
let second = tracing_subscriber::fmt().try_init();
assert!(
second.is_err(),
"init_tracing must have installed a global subscriber (second install should be rejected)"
);
}
}