Skip to main content

formualizer_eval/
telemetry.rs

1#[cfg(any(feature = "tracing", feature = "tracing_chrome"))]
2use std::sync::OnceLock;
3
4#[cfg(feature = "tracing_chrome")]
5use std::sync::Mutex;
6
7/// Initialize tracing subscriber based on env vars.
8/// - FZ_TRACING_CHROME=/path/to/trace.json (requires feature `tracing_chrome`)
9/// - FZ_TRACING=1 enables a fmt subscriber with optional FZ_TRACING_FILTER (e.g., "info,formualizer_eval=debug").
10///
11/// No-op if already initialized or when feature is disabled.
12#[cfg(feature = "tracing")]
13pub fn init_tracing_from_env() -> bool {
14    static INIT: OnceLock<bool> = OnceLock::new();
15    *INIT.get_or_init(|| {
16        let chrome_path = std::env::var("FZ_TRACING_CHROME").ok();
17        if let Some(path) = chrome_path {
18            #[cfg(feature = "tracing_chrome")]
19            {
20                use tracing_chrome::ChromeLayerBuilder;
21                use tracing_subscriber::{prelude::*, registry};
22                let (chrome_layer, guard) = ChromeLayerBuilder::new()
23                    .include_args(true)
24                    .file(path)
25                    .build();
26                // keep guard alive for process lifetime
27                if let Ok(mut slot) = CHROME_GUARD.get_or_init(|| Mutex::new(None)).lock() {
28                    *slot = Some(guard);
29                }
30                let fmt_layer = tracing_subscriber::fmt::layer().with_target(false);
31                registry().with(chrome_layer).with(fmt_layer).init();
32                return true;
33            }
34            #[cfg(not(feature = "tracing_chrome"))]
35            {
36                // Fallback to fmt when chrome not available
37                install_fmt();
38                return true;
39            }
40        }
41
42        match std::env::var("FZ_TRACING").ok().as_deref() {
43            Some("1") | Some("true") | Some("TRUE") => {
44                install_fmt();
45                true
46            }
47            _ => false,
48        }
49    })
50}
51
52#[cfg(feature = "tracing")]
53fn install_fmt() {
54    use tracing_subscriber::{EnvFilter, fmt};
55    let filter = std::env::var("FZ_TRACING_FILTER").unwrap_or_else(|_| "info".to_string());
56    let _ = fmt()
57        .with_env_filter(EnvFilter::new(filter))
58        .with_target(false)
59        .try_init();
60}
61
62#[cfg(feature = "tracing_chrome")]
63static CHROME_GUARD: OnceLock<Mutex<Option<tracing_chrome::FlushGuard>>> = OnceLock::new();
64
65#[cfg(not(feature = "tracing"))]
66pub fn init_tracing_from_env() -> bool {
67    false
68}