use std::path::PathBuf;
use clap::Parser;
use tracing::Level;
use tracing_subscriber::{fmt, EnvFilter};
#[derive(Debug, Clone, Default, Parser)]
pub struct LogArgs {
#[arg(short = 'v', action = clap::ArgAction::Count, global = true)]
pub verbose: u8,
#[arg(long = "log.file", visible_aliases = ["log-file"], global = true)]
pub log_file: Option<PathBuf>,
#[arg(long = "log.no-color", visible_aliases = ["log-no-color"], global = true)]
pub log_no_color: bool,
}
impl LogArgs {
pub fn init(&self) {
let filter = if std::env::var("RUST_LOG").is_ok() {
EnvFilter::from_default_env()
} else if self.verbose == 0 {
EnvFilter::new("off")
} else {
let level = match self.verbose {
1 => Level::ERROR,
2 => Level::WARN,
3 => Level::INFO,
4 => Level::DEBUG,
_ => Level::TRACE,
};
EnvFilter::new(format!("mega_evme={level},mega_evm={level}"))
};
let show_target = self.verbose >= 4;
if let Some(ref log_file) = self.log_file {
match std::fs::File::create(log_file) {
Ok(file) => {
fmt()
.with_env_filter(filter)
.with_target(show_target)
.with_writer(file)
.with_ansi(false)
.init();
}
Err(e) => {
eprintln!("Failed to create log file '{}': {}", log_file.display(), e);
fmt()
.with_env_filter(filter)
.with_target(show_target)
.with_writer(std::io::stderr)
.with_ansi(!self.log_no_color)
.init();
}
}
} else {
fmt()
.with_env_filter(filter)
.with_target(show_target)
.with_writer(std::io::stderr)
.with_ansi(!self.log_no_color)
.init();
}
}
}