use tracing_subscriber::{fmt, layer::SubscriberExt, util::SubscriberInitExt, EnvFilter};
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum TransportMode {
Stdio,
Stream,
}
pub fn init_logging(
mode: TransportMode,
log_file: Option<String>,
) -> Result<(), Box<dyn std::error::Error>> {
match mode {
TransportMode::Stdio => {
if let Some(filename) = log_file {
init_file_logging(filename)?;
}
}
TransportMode::Stream => {
if let Some(filename) = log_file {
init_dual_logging(filename)?;
} else {
init_console_logging()?;
}
}
}
Ok(())
}
fn init_console_logging() -> Result<(), Box<dyn std::error::Error>> {
tracing_subscriber::registry()
.with(EnvFilter::try_from_default_env().unwrap_or_else(|_| "info".into()))
.with(fmt::layer().with_writer(std::io::stderr))
.init();
Ok(())
}
fn init_file_logging(filename: String) -> Result<(), Box<dyn std::error::Error>> {
let file = std::fs::OpenOptions::new()
.create(true)
.append(true)
.open(&filename)?;
tracing_subscriber::registry()
.with(EnvFilter::try_from_default_env().unwrap_or_else(|_| "info".into()))
.with(fmt::layer().with_writer(file).with_ansi(false))
.init();
Ok(())
}
fn init_dual_logging(filename: String) -> Result<(), Box<dyn std::error::Error>> {
let file = std::fs::OpenOptions::new()
.create(true)
.append(true)
.open(&filename)?;
tracing_subscriber::registry()
.with(EnvFilter::try_from_default_env().unwrap_or_else(|_| "info".into()))
.with(fmt::layer().with_writer(std::io::stderr))
.with(fmt::layer().with_writer(file).with_ansi(false))
.init();
Ok(())
}