init4_bin_base/utils/
tracing.rs

1use crate::utils::otlp::{OtelConfig, OtelGuard};
2use tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt, Layer};
3
4/// Init tracing, returning an optional guard for the OTEL provider.
5///
6/// If the OTEL environment variables are not set, this function will
7/// initialize a basic tracing subscriber with a `fmt` layer. If the
8/// environment variables are set, it will initialize the OTEL provider
9/// with the specified configuration, as well as the `fmt` layer.
10///
11/// See [`OtelConfig`] documentation for env var information.
12///
13/// ## Panics
14///
15/// This function will panic if a global subscriber has already been set.
16///
17/// [`OtelConfig`]: crate::utils::otlp::OtelConfig
18pub fn init_tracing() -> Option<OtelGuard> {
19    let registry = tracing_subscriber::registry().with(
20        tracing_subscriber::fmt::layer()
21            .with_filter(tracing_subscriber::filter::EnvFilter::from_default_env()),
22    );
23
24    if let Some(cfg) = OtelConfig::load() {
25        let guard = cfg.provider();
26        registry.with(guard.layer()).init();
27        Some(guard)
28    } else {
29        registry.init();
30        None
31    }
32}