Skip to main content

docspec_http/
tracing_init.rs

1//! Tracing subscriber initialization.
2
3use tracing_subscriber::{layer::SubscriberExt as _, util::SubscriberInitExt as _, Layer as _};
4
5/// Installs a hardcoded tracing subscriber writing to stderr at INFO level with pretty format.
6///
7/// # Panics
8///
9/// Panics if a global subscriber has already been installed. In tests, use [`try_init`] instead.
10#[inline]
11pub fn init() {
12    let fmt = tracing_subscriber::fmt::layer()
13        .with_writer(std::io::stderr)
14        .pretty()
15        .with_filter(tracing::level_filters::LevelFilter::INFO);
16
17    #[cfg(feature = "sentry")]
18    tracing_subscriber::registry()
19        .with(fmt)
20        .with(crate::telemetry::tracing_layer())
21        .init();
22
23    #[cfg(not(feature = "sentry"))]
24    tracing_subscriber::registry().with(fmt).init();
25}
26
27/// Installs the tracing subscriber, returning an error if one is already set.
28///
29/// Use this in tests to avoid panics from double-initialization.
30///
31/// # Errors
32///
33/// Returns [`Err`] if a global subscriber has already been installed.
34#[inline]
35#[allow(clippy::std_instead_of_core)]
36// Reason: `std::error::Error` is not available in `core`; the `tracing_subscriber`
37// crate's `try_init` error type requires `std::error::Error + Send + Sync`.
38pub fn try_init() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
39    let fmt = tracing_subscriber::fmt::layer()
40        .with_writer(std::io::stderr)
41        .pretty()
42        .with_filter(tracing::level_filters::LevelFilter::INFO);
43
44    #[cfg(feature = "sentry")]
45    return tracing_subscriber::registry()
46        .with(fmt)
47        .with(crate::telemetry::tracing_layer())
48        .try_init()
49        .map_err(Into::into);
50
51    #[cfg(not(feature = "sentry"))]
52    tracing_subscriber::registry()
53        .with(fmt)
54        .try_init()
55        .map_err(Into::into)
56}