Skip to main content

core_lib/log/
tracing.rs

1//! Structured logging (`tracing`) support.
2//!
3//! A subscriber is always installed at boot. Events carrying a `log_path`
4//! field are appended to the matching per-watch log file by
5//! [`super::file_layer::FileLayer`], while the same events are mirrored to
6//! stderr when `RUST_LOG` allows (default: info and above).
7//!
8//! stderr is used on purpose: the dashboard (`fleet stats`) owns stdout, and
9//! stderr keeps logs interleaved safely with it.
10
11use std::sync::OnceLock;
12
13use tracing::level_filters::LevelFilter;
14use tracing_subscriber::{
15    EnvFilter, Layer, layer::SubscriberExt, registry, util::SubscriberInitExt,
16};
17
18use super::file_layer::FileLayer;
19
20static INIT: OnceLock<()> = OnceLock::new();
21
22/// Install the global subscriber exactly once. Safe to call repeatedly; a
23/// second call is a no-op (whether or not another subscriber was registered).
24pub fn init_tracing() {
25    INIT.get_or_init(|| {
26        let filter = EnvFilter::builder()
27            .with_default_directive(LevelFilter::INFO.into())
28            .from_env_lossy();
29
30        // `FLEET_NO_COLOR` applies to the per-watch log files (honored by
31        // `FileLayer`) but must also keep the stderr mirror free of ANSI
32        // codes, in particular when stderr is piped.
33        let ansi = std::env::var("FLEET_NO_COLOR").is_err();
34
35        let _ = registry()
36            .with(FileLayer::new())
37            .with(
38                tracing_subscriber::fmt::layer()
39                    .with_writer(std::io::stderr)
40                    .with_ansi(ansi)
41                    .with_filter(filter),
42            )
43            .try_init()
44            // A subscriber installed before us (embedding harness) silently
45            // drops the file layer: say so instead of losing per-watch logs.
46            .map_err(|e| {
47                tracing::error!(
48                    target: "fleet",
49                    message = %format!("fleet.tracing: failed to install subscriber: {e}"),
50                );
51            });
52    });
53}