Skip to main content

cornerstone/
log.rs

1//! Logging: a leveled logger separate from the user-facing [`crate::out`]
2//! helpers. `out` is for what the user reads; `log` is for diagnostics that can
3//! also be written to a file. Levels map to verbosity: `-v` enables debug, `-vv`
4//! enables trace. A file sink, if set, always records every level regardless of
5//! console verbosity, so a quiet run still leaves a full trace on disk.
6
7use crate::style as s;
8use std::fs::{File, OpenOptions};
9use std::io::Write;
10use std::sync::Mutex;
11use std::sync::OnceLock;
12
13/// Severity levels, ordered.
14#[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
50/// Attach a file sink. Every log record is appended, with a millisecond
51/// timestamp, regardless of console verbosity. Call once at startup. Returns an
52/// error if the file can't be opened.
53pub 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
65/// The console level derived from verbosity: 0 → Info, 1 → Debug, 2+ → Trace.
66fn console_level() -> Level {
67    match crate::out::verbosity() {
68        0 => Level::Info,
69        1 => Level::Debug,
70        _ => Level::Trace,
71    }
72}
73
74/// Emit a log record at `level`. Goes to stderr if within console verbosity and
75/// not quiet; always goes to the file sink if one is attached.
76pub fn log(level: Level, msg: &str) {
77    // File sink: unconditional.
78    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    // Console: gated by verbosity and quiet.
85    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
109/// A simple millisecond timestamp (seconds since the Unix epoch with millis),
110/// avoiding a chrono dependency. Format: `<secs>.<millis>`.
111fn 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}