use std::{fmt, io, sync::Arc};
use dotenv::dotenv;
use tracing::subscriber::DefaultGuard;
use tracing_subscriber::{EnvFilter, filter::ParseError};
#[derive(Clone, Debug, thiserror::Error)]
pub(crate) enum Error {
#[allow(dead_code)]
Io(Arc<io::Error>),
#[allow(dead_code)]
Message(String),
#[allow(dead_code)]
ParseFilter(Arc<ParseError>),
Parse(#[from] url::ParseError),
Protocol(#[from] tansu_sans_io::Error),
Storage(#[from] tansu_storage::Error),
}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{self:?}")
}
}
impl From<io::Error> for Error {
fn from(value: io::Error) -> Self {
Self::Io(Arc::new(value))
}
}
impl From<ParseError> for Error {
fn from(value: ParseError) -> Self {
Self::ParseFilter(Arc::new(value))
}
}
pub(crate) fn init_tracing() -> Result<DefaultGuard, Error> {
use std::{fs::File, sync::Arc, thread};
_ = dotenv().ok();
Ok(tracing::subscriber::set_default(
tracing_subscriber::fmt()
.with_level(true)
.with_line_number(true)
.with_thread_names(false)
.with_env_filter(
EnvFilter::from_default_env()
.add_directive(format!("{}=debug", env!("CARGO_CRATE_NAME")).parse()?),
)
.with_writer(
thread::current()
.name()
.ok_or(Error::Message(String::from("unnamed thread")))
.and_then(|name| {
File::create(format!(
"../logs/{}/{}::{name}.log",
env!("CARGO_PKG_NAME"),
env!("CARGO_CRATE_NAME")
))
.map_err(Into::into)
})
.map(Arc::new)?,
)
.finish(),
))
}