mermaid_cli/utils/
logger.rs1use std::fs::OpenOptions;
2use std::path::PathBuf;
3use tracing::{debug, error, info, warn};
4use tracing_subscriber::{EnvFilter, layer::SubscriberExt, util::SubscriberInitExt};
5
6fn get_log_file_path() -> Option<PathBuf> {
8 std::env::var("HOME")
9 .ok()
10 .map(|home| PathBuf::from(home).join(".mermaid").join("mermaid.log"))
11}
12
13pub fn init_logger(verbose: bool) {
15 let filter = if verbose {
18 EnvFilter::new("debug,mermaid=debug")
19 } else {
20 EnvFilter::try_from_default_env().unwrap_or_else(|_| EnvFilter::new("warn,mermaid=info"))
21 };
22
23 if let Some(log_path) = get_log_file_path() {
26 if let Some(parent) = log_path.parent() {
28 let _ = std::fs::create_dir_all(parent);
29 }
30
31 if let Ok(file) = OpenOptions::new().create(true).append(true).open(&log_path) {
33 let fmt_layer = tracing_subscriber::fmt::layer()
34 .with_writer(file)
35 .with_target(false)
36 .with_thread_ids(false)
37 .with_thread_names(false)
38 .with_ansi(false) .compact();
40
41 tracing_subscriber::registry()
42 .with(filter)
43 .with(fmt_layer)
44 .init();
45 return;
46 }
47 }
48
49 tracing_subscriber::registry().with(filter).init();
51}
52
53pub fn log_info(category: &str, message: impl std::fmt::Display) {
55 info!(category = %category, "{}", message);
56}
57
58pub fn log_warn(category: &str, message: impl std::fmt::Display) {
60 warn!(category = %category, "{}", message);
61}
62
63pub fn log_error(category: &str, message: impl std::fmt::Display) {
65 error!(category = %category, "{}", message);
66}
67
68pub fn log_debug(message: impl std::fmt::Display) {
70 debug!("{}", message);
71}
72
73pub fn log_progress(step: usize, total: usize, message: impl std::fmt::Display) {
75 info!(step = step, total = total, "{}", message);
76}