use std::{error::Error, fmt};
use tracing_core::dispatcher::{self, Dispatch};
#[cfg(feature = "tracing-log")]
use tracing_log::AsLog;
pub trait SubscriberInitExt
where
Self: Into<Dispatch>,
{
fn set_default(self) -> dispatcher::DefaultGuard {
#[cfg(feature = "tracing-log")]
let _ = tracing_log::LogTracer::init();
dispatcher::set_default(&self.into())
}
fn try_init(self) -> Result<(), TryInitError> {
dispatcher::set_global_default(self.into()).map_err(TryInitError::new)?;
#[cfg(feature = "tracing-log")]
tracing_log::LogTracer::builder()
.with_max_level(tracing_core::LevelFilter::current().as_log())
.init()
.map_err(TryInitError::new)?;
Ok(())
}
fn init(self) {
self.try_init()
.expect("failed to set global default subscriber")
}
}
impl<T> SubscriberInitExt for T where T: Into<Dispatch> {}
pub struct TryInitError {
inner: Box<dyn Error + Send + Sync + 'static>,
}
impl TryInitError {
fn new(e: impl Into<Box<dyn Error + Send + Sync + 'static>>) -> Self {
Self { inner: e.into() }
}
}
impl fmt::Debug for TryInitError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Debug::fmt(&self.inner, f)
}
}
impl fmt::Display for TryInitError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Display::fmt(&self.inner, f)
}
}
impl Error for TryInitError {
fn source(&self) -> Option<&(dyn Error + 'static)> {
self.inner.source()
}
}