use crate::style as s;
use std::fs::{File, OpenOptions};
use std::io::Write;
use std::sync::Mutex;
use std::sync::OnceLock;
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub enum Level {
Error,
Warn,
Info,
Debug,
Trace,
}
impl Level {
fn label(self) -> &'static str {
match self {
Level::Error => "ERROR",
Level::Warn => "WARN",
Level::Info => "INFO",
Level::Debug => "DEBUG",
Level::Trace => "TRACE",
}
}
fn paint(self, text: &str) -> String {
match self {
Level::Error => s::red(text),
Level::Warn => s::yellow(text),
Level::Info => s::cyan(text),
Level::Debug => s::gray(text),
Level::Trace => s::dim(text),
}
}
}
struct Sink {
file: Mutex<File>,
}
static SINK: OnceLock<Sink> = OnceLock::new();
pub fn set_file(path: &str) -> crate::error::Result<()> {
let file = OpenOptions::new()
.create(true)
.append(true)
.open(path)
.map_err(|e| crate::error::Error::msg(format!("cannot open log file {}: {}", path, e)))?;
let _ = SINK.set(Sink {
file: Mutex::new(file),
});
Ok(())
}
fn console_level() -> Level {
match crate::out::verbosity() {
0 => Level::Info,
1 => Level::Debug,
_ => Level::Trace,
}
}
pub fn log(level: Level, msg: &str) {
if let Some(sink) = SINK.get() {
let ts = timestamp();
if let Ok(mut f) = sink.file.lock() {
let _ = writeln!(f, "{} {:<5} {}", ts, level.label(), msg);
}
}
if crate::out::is_quiet() && level > Level::Warn {
return;
}
if level <= console_level() {
eprintln!("{} {}", level.paint(level.label()), msg);
}
}
pub fn error(msg: &str) {
log(Level::Error, msg);
}
pub fn warn(msg: &str) {
log(Level::Warn, msg);
}
pub fn info(msg: &str) {
log(Level::Info, msg);
}
pub fn debug(msg: &str) {
log(Level::Debug, msg);
}
pub fn trace(msg: &str) {
log(Level::Trace, msg);
}
fn timestamp() -> String {
let now = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap_or_default();
format!("{}.{:03}", now.as_secs(), now.subsec_millis())
}