use std::fs::OpenOptions;
use std::path::PathBuf;
use tracing::{debug, error, info, warn};
use tracing_subscriber::{EnvFilter, layer::SubscriberExt, util::SubscriberInitExt};
fn get_log_file_path() -> Option<PathBuf> {
std::env::var("HOME")
.ok()
.map(|home| PathBuf::from(home).join(".mermaid").join("mermaid.log"))
}
pub fn init_logger(verbose: bool) {
let filter = if verbose {
EnvFilter::new("debug,mermaid=debug")
} else {
EnvFilter::try_from_default_env().unwrap_or_else(|_| EnvFilter::new("warn,mermaid=info"))
};
if let Some(log_path) = get_log_file_path() {
if let Some(parent) = log_path.parent() {
let _ = std::fs::create_dir_all(parent);
}
if let Ok(file) = OpenOptions::new().create(true).append(true).open(&log_path) {
let fmt_layer = tracing_subscriber::fmt::layer()
.with_writer(file)
.with_target(false)
.with_thread_ids(false)
.with_thread_names(false)
.with_ansi(false) .compact();
tracing_subscriber::registry()
.with(filter)
.with(fmt_layer)
.init();
return;
}
}
tracing_subscriber::registry().with(filter).init();
}
pub fn log_info(category: &str, message: impl std::fmt::Display) {
info!(category = %category, "{}", message);
}
pub fn log_warn(category: &str, message: impl std::fmt::Display) {
warn!(category = %category, "{}", message);
}
pub fn log_error(category: &str, message: impl std::fmt::Display) {
error!(category = %category, "{}", message);
}
pub fn log_debug(message: impl std::fmt::Display) {
debug!("{}", message);
}
pub fn log_progress(step: usize, total: usize, message: impl std::fmt::Display) {
info!(step = step, total = total, "{}", message);
}