1use crate::style as s;
8use std::fs::{File, OpenOptions};
9use std::io::Write;
10use std::sync::Mutex;
11use std::sync::OnceLock;
12
13#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
15pub enum Level {
16 Error,
17 Warn,
18 Info,
19 Debug,
20 Trace,
21}
22
23impl Level {
24 fn label(self) -> &'static str {
25 match self {
26 Level::Error => "ERROR",
27 Level::Warn => "WARN",
28 Level::Info => "INFO",
29 Level::Debug => "DEBUG",
30 Level::Trace => "TRACE",
31 }
32 }
33 fn paint(self, text: &str) -> String {
34 match self {
35 Level::Error => s::red(text),
36 Level::Warn => s::yellow(text),
37 Level::Info => s::cyan(text),
38 Level::Debug => s::gray(text),
39 Level::Trace => s::dim(text),
40 }
41 }
42}
43
44struct Sink {
45 file: Mutex<File>,
46}
47
48static SINK: OnceLock<Sink> = OnceLock::new();
49
50pub fn set_file(path: &str) -> crate::error::Result<()> {
54 let file = OpenOptions::new()
55 .create(true)
56 .append(true)
57 .open(path)
58 .map_err(|e| crate::error::Error::msg(format!("cannot open log file {}: {}", path, e)))?;
59 let _ = SINK.set(Sink {
60 file: Mutex::new(file),
61 });
62 Ok(())
63}
64
65fn console_level() -> Level {
67 match crate::out::verbosity() {
68 0 => Level::Info,
69 1 => Level::Debug,
70 _ => Level::Trace,
71 }
72}
73
74pub fn log(level: Level, msg: &str) {
77 if let Some(sink) = SINK.get() {
79 let ts = timestamp();
80 if let Ok(mut f) = sink.file.lock() {
81 let _ = writeln!(f, "{} {:<5} {}", ts, level.label(), msg);
82 }
83 }
84 if crate::out::is_quiet() && level > Level::Warn {
86 return;
87 }
88 if level <= console_level() {
89 eprintln!("{} {}", level.paint(level.label()), msg);
90 }
91}
92
93pub fn error(msg: &str) {
94 log(Level::Error, msg);
95}
96pub fn warn(msg: &str) {
97 log(Level::Warn, msg);
98}
99pub fn info(msg: &str) {
100 log(Level::Info, msg);
101}
102pub fn debug(msg: &str) {
103 log(Level::Debug, msg);
104}
105pub fn trace(msg: &str) {
106 log(Level::Trace, msg);
107}
108
109fn timestamp() -> String {
112 let now = std::time::SystemTime::now()
113 .duration_since(std::time::UNIX_EPOCH)
114 .unwrap_or_default();
115 format!("{}.{:03}", now.as_secs(), now.subsec_millis())
116}