formualizer_eval/
telemetry.rs

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