init4_bin_base/utils/
tracing.rs

1use crate::utils::{
2    from_env::FromEnvVar,
3    otlp::{OtelConfig, OtelGuard},
4};
5use tracing_subscriber::{filter::EnvFilter, layer::SubscriberExt, util::SubscriberInitExt, Layer};
6
7const TRACING_LOG_JSON: &str = "TRACING_LOG_JSON";
8
9/// Install a format layer based on the `TRACING_LOG_JSON` environment
10/// variable, and then install the registr
11///
12macro_rules! install_fmt {
13    (json @ $registry:ident, $filter:ident) => {{
14        let fmt = tracing_subscriber::fmt::layer().json().with_filter($filter);
15        $registry.with(fmt).init();
16    }};
17    (log @ $registry:ident, $filter:ident) => {{
18        let fmt = tracing_subscriber::fmt::layer().with_filter($filter);
19        $registry.with(fmt).init();
20    }};
21    ($registry:ident) => {{
22        let json = bool::from_env_var(TRACING_LOG_JSON).unwrap_or(false);
23        let filter = EnvFilter::from_default_env();
24        if json {
25            install_fmt!(json @ $registry, filter);
26        } else {
27            install_fmt!(log @ $registry, filter);
28        }
29    }};
30}
31
32/// Init tracing, returning an optional guard for the OTEL provider.
33///
34/// If the OTEL environment variables are not set, this function will
35/// initialize a basic tracing subscriber with a `fmt` layer. If the
36/// environment variables are set, it will initialize the OTEL provider
37/// with the specified configuration, as well as the `fmt` layer.
38///
39/// ## Env Reads
40///
41/// - `TRACING_LOG_JSON` - If set, will enable JSON logging.
42/// - As [`OtelConfig`] documentation for env var information.
43///
44/// ## Panics
45///
46/// This function will panic if a global subscriber has already been set.
47///
48/// [`OtelConfig`]: crate::utils::otlp::OtelConfig
49pub fn init_tracing() -> Option<OtelGuard> {
50    let registry = tracing_subscriber::registry();
51
52    if let Some(cfg) = OtelConfig::load() {
53        let guard = cfg.provider();
54        let registry = registry.with(guard.layer());
55        install_fmt!(registry);
56        Some(guard)
57    } else {
58        install_fmt!(registry);
59        None
60    }
61}