Skip to main content

nsh_engine/
logging.rs

1//! The logger of the desktop release runners (`nsh-macos-app`,
2//! `nsh-windows-app`, `nsh-linux-app`): one filter, one rolling file in the
3//! app's data directory, and the platform's own place for each line.
4//!
5//! - What is logged: `RUST_LOG` when it is set, in `env_logger`'s syntax
6//!   (`info`, `my_app=debug,js=info`, `warn,nsh_engine::updates=info`); else
7//!   the runners' rule, warnings, errors and the app's `js` lines
8//!   (`console.*`), and every line from info up when run by `nsh run`.
9//! - Where: a rolling file, `app.log` in the directory `nsh.json`
10//!   `"logDir"` names, else `logs` in the app's data directory
11//!   ([`log_directory`], [`log_dir`]), whose path apps read (`nsh_core::element::log_file`, TS
12//!   `process.logFile`), and the platform's output the runner hands
13//!   [`LogOptions::output`] (the unified log, the debugger's output,
14//!   stderr).
15//! - The file: one line per record, `<UTC time> <LEVEL> <target>: <message>`.
16//!   Past [`MAX_FILE_BYTES`] it becomes `app.1.log` (the one before that
17//!   `app.2.log`, ...) and a new `app.log` starts; [`KEPT_FILES`] older files
18//!   are kept. A file that cannot be made or written is left alone, tried
19//!   again after [`RETRY_AFTER`]: the app and the platform's output carry
20//!   on without it.
21//! - Panics: written to the file whatever the filter, as `ERROR panic:`
22//!   lines in the words Rust prints them in (with a backtrace when
23//!   `RUST_BACKTRACE` asks for one), and then handed to the hook the
24//!   process had, which prints them to stderr as before. A packaged app's
25//!   stderr is often nowhere (a Windows GUI program, a Mac app opened from
26//!   Finder), so the file is where a crash can be read.
27
28use std::{
29    any::Any,
30    backtrace::{Backtrace, BacktraceStatus},
31    fs::{File, OpenOptions},
32    io::Write as _,
33    panic::{Location, PanicHookInfo},
34    path::{Path, PathBuf},
35    sync::{Mutex, OnceLock, PoisonError, TryLockError},
36    time::{Duration, Instant, SystemTime, UNIX_EPOCH},
37};
38
39use log::{Level, LevelFilter, Log, Metadata, Record};
40
41/// The size past which the log file rolls over to `app.1.log`.
42pub const MAX_FILE_BYTES: u64 = 5 * 1024 * 1024;
43
44/// How many rolled-over files are kept beside `app.log` (`app.1.log` up to
45/// `app.<KEPT_FILES>.log`).
46pub const KEPT_FILES: usize = 3;
47
48/// How long the logger waits before it tries again to open a log file it
49/// could not open or write.
50pub const RETRY_AFTER: Duration = Duration::from_secs(30);
51
52/// The log file's name (and the stem of the rolled-over ones).
53const FILE_STEM: &str = "app";
54
55/// The environment variable of the filter.
56const FILTER_VARIABLE: &str = "RUST_LOG";
57
58/// The platform's own place for each line the filter lets through.
59pub type LogOutput = Box<dyn Fn(&Record<'_>) + Send + Sync>;
60
61/// What [`install`] sets up.
62#[non_exhaustive]
63#[derive(Default)]
64pub struct LogOptions {
65    /// Run by `nsh run`: every line from info up when `RUST_LOG` is not set.
66    pub development: bool,
67    /// The directory of the log files ([`log_dir`]); `None` writes none.
68    pub directory: Option<PathBuf>,
69    /// The platform's own place for each line the filter lets through.
70    pub output: Option<LogOutput>,
71}
72
73/// The directory of the log files of app `app_id` when it names no data
74/// directory of its own: `logs` in the one under the system's directory
75/// for apps' data (`<support dir>/<app id>/logs`). `None` where the system
76/// has none.
77pub fn log_dir(app_id: &str) -> Option<PathBuf> {
78    crate::support_dir().map(|dir| dir.join(crate::app_dir_name(Some(app_id))).join("logs"))
79}
80
81/// The directory the desktop runners write the log files of app `app_id`
82/// in: `log_dir` (`nsh.json` `"logDir"`, already resolved) when the app names
83/// one, else `logs` in `data_dir` (`"dataDir"`), else [`log_dir`]'s default.
84pub fn log_directory(
85    app_id: &str,
86    data_dir: Option<&Path>,
87    log_dir_override: Option<&Path>,
88) -> Option<PathBuf> {
89    match (log_dir_override, data_dir) {
90        (Some(dir), _) => Some(dir.to_path_buf()),
91        (None, Some(dir)) => Some(dir.join("logs")),
92        (None, None) => log_dir(app_id),
93    }
94}
95
96/// Makes the runners' logger the process's logger, filtered by `RUST_LOG`
97/// when it is set, and records its file for `nsh_core::element::log_file`.
98/// Returns whether it did: `false` when the process has a logger already.
99pub fn install(options: LogOptions) -> bool {
100    static LOGGER: OnceLock<Logger> = OnceLock::new();
101    let filter = std::env::var(FILTER_VARIABLE).ok();
102    let mut installed = false;
103    let logger = LOGGER.get_or_init(|| {
104        installed = true;
105        Logger::new(options, filter.as_deref())
106    });
107    if !installed || log::set_logger(logger).is_err() {
108        return false;
109    }
110    log::set_max_level(logger.filter.max_level());
111    if let Some(file) = &logger.file {
112        nsh_core::log_file::set(file.lock().unwrap_or_else(PoisonError::into_inner).path());
113        std::panic::set_hook(log_panics(logger, std::panic::take_hook()));
114    }
115    if let Some(error) = &logger.filter_error {
116        log::warn!("{FILTER_VARIABLE} is not a filter ({error}); the default levels apply");
117    }
118    true
119}
120
121pub(crate) struct Logger {
122    filter: Filter,
123    /// Why `RUST_LOG` was not used, to say once the logger is in place.
124    filter_error: Option<String>,
125    file: Option<Mutex<RollingFile>>,
126    output: Option<LogOutput>,
127}
128
129impl Logger {
130    /// The logger of `options`, filtered by `filter` (`RUST_LOG`'s value).
131    pub(crate) fn new(options: LogOptions, filter: Option<&str>) -> Logger {
132        let (filter, filter_error) = Filter::new(filter, options.development);
133        Logger {
134            filter,
135            filter_error,
136            file: options
137                .directory
138                .map(|dir| Mutex::new(RollingFile::new(dir))),
139            output: options.output,
140        }
141    }
142}
143
144impl Logger {
145    /// Writes a panic's description to the file, whatever the filter: a
146    /// crash is what the file is read for, and a packaged app's stderr,
147    /// where Rust prints it, is often nowhere (a Windows GUI program, a Mac
148    /// app opened from Finder).
149    fn write_panic(&self, text: &str) {
150        let Some(file) = &self.file else {
151            return;
152        };
153        let line = format!("{} ERROR panic: {text}\n", Timestamp(SystemTime::now()));
154        // The panic may come from this thread while it writes a line: wait
155        // a little for the file, never forever.
156        for _ in 0..PANIC_LOCK_TRIES {
157            match file.try_lock() {
158                Ok(mut file) => return file.write(line.as_bytes(), Instant::now()),
159                Err(TryLockError::Poisoned(poisoned)) => {
160                    return poisoned.into_inner().write(line.as_bytes(), Instant::now());
161                }
162                Err(TryLockError::WouldBlock) => std::thread::sleep(Duration::from_millis(1)),
163            }
164        }
165    }
166}
167
168/// A panic hook, as `std::panic::set_hook` takes it.
169type PanicHook = dyn Fn(&PanicHookInfo<'_>) + Send + Sync + 'static;
170
171/// How many times a panic tries the file, a millisecond apart, before its
172/// line is given up.
173const PANIC_LOCK_TRIES: usize = 100;
174
175/// The panic hook that writes each panic to `logger`'s file (with a
176/// backtrace when `RUST_BACKTRACE` asks for one) and then runs `previous`,
177/// which prints it to stderr as before.
178fn log_panics(logger: &'static Logger, previous: Box<PanicHook>) -> Box<PanicHook> {
179    Box::new(move |info| {
180        let thread = std::thread::current();
181        let mut text = panic_text(thread.name(), info.location(), info.payload());
182        let backtrace = Backtrace::capture();
183        if backtrace.status() == BacktraceStatus::Captured {
184            text.push_str(&format!("\nstack backtrace:\n{backtrace}"));
185        }
186        logger.write_panic(text.trim_end());
187        previous(info);
188    })
189}
190
191/// A panic described as Rust's own hook prints it: `thread '<name>'
192/// panicked at <file>:<line>:<column>:` and the message on the next line.
193fn panic_text(
194    thread: Option<&str>,
195    location: Option<&Location<'_>>,
196    payload: &(dyn Any + Send),
197) -> String {
198    let message = payload
199        .downcast_ref::<&str>()
200        .copied()
201        .or_else(|| payload.downcast_ref::<String>().map(String::as_str))
202        .unwrap_or("Box<dyn Any>");
203    let thread = thread.unwrap_or("<unnamed>");
204    match location {
205        Some(at) => format!(
206            "thread '{thread}' panicked at {}:{}:{}:\n{message}",
207            at.file(),
208            at.line(),
209            at.column()
210        ),
211        None => format!("thread '{thread}' panicked:\n{message}"),
212    }
213}
214
215impl Log for Logger {
216    fn enabled(&self, metadata: &Metadata<'_>) -> bool {
217        self.filter.enabled(metadata)
218    }
219
220    fn log(&self, record: &Record<'_>) {
221        if !self.filter.matches(record) {
222            return;
223        }
224        if let Some(file) = &self.file {
225            let line = format!(
226                "{} {:<5} {}: {}\n",
227                Timestamp(SystemTime::now()),
228                record.level(),
229                record.target(),
230                record.args()
231            );
232            file.lock()
233                .unwrap_or_else(PoisonError::into_inner)
234                .write(line.as_bytes(), Instant::now());
235        }
236        if let Some(output) = &self.output {
237            output(record);
238        }
239    }
240
241    fn flush(&self) {}
242}
243
244/// Which records are logged.
245enum Filter {
246    /// Warnings, errors and `js` lines from info up; every line from info
247    /// up in development.
248    Default { development: bool },
249    /// `RUST_LOG`'s.
250    Env(env_filter::Filter),
251}
252
253impl Filter {
254    /// `RUST_LOG`'s filter when `value` is one, else the default (and why
255    /// `value` is not one).
256    fn new(value: Option<&str>, development: bool) -> (Filter, Option<String>) {
257        let default = Filter::Default { development };
258        let Some(value) = value.map(str::trim).filter(|value| !value.is_empty()) else {
259            return (default, None);
260        };
261        match env_filter::Builder::new().try_parse(value) {
262            Ok(builder) => (Filter::Env(builder.build()), None),
263            Err(error) => (default, Some(error.to_string())),
264        }
265    }
266
267    fn max_level(&self) -> LevelFilter {
268        match self {
269            Filter::Default { .. } => LevelFilter::Info,
270            Filter::Env(filter) => filter.filter(),
271        }
272    }
273
274    fn enabled(&self, metadata: &Metadata<'_>) -> bool {
275        match self {
276            Filter::Default { development } => {
277                metadata.level() <= Level::Warn
278                    || (metadata.level() <= Level::Info
279                        && (*development || metadata.target() == "js"))
280            }
281            Filter::Env(filter) => filter.enabled(metadata),
282        }
283    }
284
285    fn matches(&self, record: &Record<'_>) -> bool {
286        match self {
287            Filter::Default { .. } => self.enabled(record.metadata()),
288            Filter::Env(filter) => filter.matches(record),
289        }
290    }
291}
292
293/// `app.log` in a directory, rolled over past [`MAX_FILE_BYTES`].
294struct RollingFile {
295    dir: PathBuf,
296    /// The open file and its size, opened on the first line.
297    open: Option<(File, u64)>,
298    /// When to try again after a failure.
299    retry_at: Option<Instant>,
300}
301
302impl RollingFile {
303    fn new(dir: PathBuf) -> RollingFile {
304        RollingFile {
305            dir,
306            open: None,
307            retry_at: None,
308        }
309    }
310
311    /// The current file, `app.log`.
312    fn path(&self) -> PathBuf {
313        self.dir.join(format!("{FILE_STEM}.log"))
314    }
315
316    /// The `n`th older file, `app.<n>.log`.
317    fn older(&self, n: usize) -> PathBuf {
318        self.dir.join(format!("{FILE_STEM}.{n}.log"))
319    }
320
321    /// Appends `line` at `now`, rolling the file over first when it would
322    /// pass [`MAX_FILE_BYTES`]. A failure closes the file until
323    /// [`RETRY_AFTER`] has passed.
324    fn write(&mut self, line: &[u8], now: Instant) {
325        if self.retry_at.is_some_and(|at| now < at) {
326            return;
327        }
328        self.retry_at = None;
329        let written = self.try_write(line);
330        if written.is_err() {
331            self.open = None;
332            self.retry_at = Some(now + RETRY_AFTER);
333        }
334    }
335
336    fn try_write(&mut self, line: &[u8]) -> std::io::Result<()> {
337        if self.open.is_none() {
338            self.open = Some(self.open_file()?);
339        }
340        let size = self.open.as_ref().map_or(0, |(_, size)| *size);
341        if size > 0 && size + line.len() as u64 > MAX_FILE_BYTES {
342            self.open = None;
343            self.roll_over()?;
344            self.open = Some(self.open_file()?);
345        }
346        let (file, size) = self.open.as_mut().expect("opened above");
347        file.write_all(line)?;
348        *size += line.len() as u64;
349        Ok(())
350    }
351
352    /// `app.log` for appending, made with its directory when missing, and
353    /// its size.
354    fn open_file(&self) -> std::io::Result<(File, u64)> {
355        std::fs::create_dir_all(&self.dir)?;
356        let file = OpenOptions::new()
357            .create(true)
358            .append(true)
359            .open(self.path())?;
360        let size = file.metadata()?.len();
361        Ok((file, size))
362    }
363
364    /// Moves each file one place older, dropping the oldest: `app.log`
365    /// becomes `app.1.log`, `app.1.log` `app.2.log`, ...
366    fn roll_over(&self) -> std::io::Result<()> {
367        // Windows' rename does not replace a file.
368        remove_if_present(&self.older(KEPT_FILES))?;
369        for n in (1..KEPT_FILES).rev() {
370            rename_if_present(&self.older(n), &self.older(n + 1))?;
371        }
372        if KEPT_FILES == 0 {
373            return remove_if_present(&self.path());
374        }
375        rename_if_present(&self.path(), &self.older(1))
376    }
377}
378
379fn remove_if_present(path: &Path) -> std::io::Result<()> {
380    match std::fs::remove_file(path) {
381        Err(error) if error.kind() != std::io::ErrorKind::NotFound => Err(error),
382        _ => Ok(()),
383    }
384}
385
386fn rename_if_present(from: &Path, to: &Path) -> std::io::Result<()> {
387    match std::fs::rename(from, to) {
388        Err(error) if error.kind() != std::io::ErrorKind::NotFound => Err(error),
389        _ => Ok(()),
390    }
391}
392
393/// A time as RFC 3339 in UTC to the millisecond: `2026-11-12T08:30:05.123Z`.
394struct Timestamp(SystemTime);
395
396impl std::fmt::Display for Timestamp {
397    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
398        let since = self.0.duration_since(UNIX_EPOCH).unwrap_or_default();
399        let secs = since.as_secs();
400        let (year, month, day) = civil_from_days((secs / 86_400) as i64);
401        let of_day = secs % 86_400;
402        write!(
403            f,
404            "{year:04}-{month:02}-{day:02}T{:02}:{:02}:{:02}.{:03}Z",
405            of_day / 3600,
406            of_day / 60 % 60,
407            of_day % 60,
408            since.subsec_millis()
409        )
410    }
411}
412
413/// The proleptic Gregorian date of `days` since 1970-01-01 (Howard
414/// Hinnant's `civil_from_days`).
415fn civil_from_days(days: i64) -> (i64, u32, u32) {
416    let z = days + 719_468;
417    let era = z.div_euclid(146_097);
418    let doe = z.rem_euclid(146_097);
419    let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365;
420    let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
421    let mp = (5 * doy + 2) / 153;
422    let day = (doy - (153 * mp + 2) / 5 + 1) as u32;
423    let month = if mp < 10 { mp + 3 } else { mp - 9 } as u32;
424    let year = yoe + era * 400 + i64::from(month <= 2);
425    (year, month, day)
426}
427
428#[cfg(test)]
429mod tests {
430    use std::sync::{Arc, Mutex};
431
432    use super::*;
433
434    /// A fresh directory under the system's temporary one.
435    fn temp_dir(name: &str) -> PathBuf {
436        let dir = std::env::temp_dir().join(format!(
437            "nsh-logging-{name}-{}-{:?}",
438            std::process::id(),
439            std::thread::current().id()
440        ));
441        let _ = std::fs::remove_dir_all(&dir);
442        dir
443    }
444
445    fn metadata(level: Level, target: &str) -> Metadata<'_> {
446        Metadata::builder().level(level).target(target).build()
447    }
448
449    fn log(logger: &Logger, level: Level, target: &str, message: &str) {
450        logger.log(
451            &Record::builder()
452                .level(level)
453                .target(target)
454                .args(format_args!("{message}"))
455                .build(),
456        );
457    }
458
459    #[test]
460    fn without_rust_log_the_runners_levels_hold() {
461        let (filter, error) = Filter::new(None, false);
462        assert!(error.is_none());
463        assert_eq!(filter.max_level(), LevelFilter::Info);
464        assert!(filter.enabled(&metadata(Level::Warn, "my_app")));
465        assert!(filter.enabled(&metadata(Level::Info, "js")));
466        assert!(!filter.enabled(&metadata(Level::Debug, "js")));
467        assert!(!filter.enabled(&metadata(Level::Info, "my_app")));
468        let (development, _) = Filter::new(Some("  "), true);
469        assert!(development.enabled(&metadata(Level::Info, "my_app")));
470        assert!(!development.enabled(&metadata(Level::Debug, "my_app")));
471    }
472
473    #[test]
474    fn rust_log_sets_the_levels() {
475        let (filter, error) =
476            Filter::new(Some("warn,my_app=debug,nsh_engine::updates=info"), false);
477        assert!(error.is_none());
478        assert_eq!(filter.max_level(), LevelFilter::Debug);
479        assert!(filter.enabled(&metadata(Level::Debug, "my_app::login")));
480        assert!(!filter.enabled(&metadata(Level::Trace, "my_app")));
481        assert!(filter.enabled(&metadata(Level::Info, "nsh_engine::updates")));
482        assert!(!filter.enabled(&metadata(Level::Info, "js")));
483        assert!(filter.enabled(&metadata(Level::Warn, "js")));
484        // A bad filter keeps the defaults, and says why.
485        let (filter, error) = Filter::new(Some("my_app=loud"), false);
486        assert!(error.is_some());
487        assert!(filter.enabled(&metadata(Level::Info, "js")));
488    }
489
490    #[test]
491    fn lines_go_to_the_file_and_the_output() {
492        let dir = temp_dir("lines");
493        let seen = Arc::new(Mutex::new(Vec::new()));
494        let output = {
495            let seen = seen.clone();
496            Box::new(move |record: &Record<'_>| {
497                seen.lock()
498                    .unwrap()
499                    .push(format!("{} {}", record.level(), record.args()));
500            })
501        };
502        let logger = Logger::new(
503            LogOptions {
504                directory: Some(dir.clone()),
505                output: Some(output),
506                ..LogOptions::default()
507            },
508            Some("info"),
509        );
510        log(&logger, Level::Info, "my_app", "signed in");
511        log(&logger, Level::Debug, "my_app", "token refreshed");
512        log(&logger, Level::Error, "js", "boom");
513        let text = std::fs::read_to_string(dir.join("app.log")).unwrap();
514        let lines: Vec<&str> = text.lines().collect();
515        assert_eq!(lines.len(), 2, "{text}");
516        assert!(lines[0].ends_with(" INFO  my_app: signed in"), "{text}");
517        assert!(lines[1].ends_with(" ERROR js: boom"), "{text}");
518        assert_eq!(&lines[0][4..5], "-");
519        assert_eq!(&lines[0][23..25], "Z ");
520        assert_eq!(*seen.lock().unwrap(), ["INFO signed in", "ERROR boom"]);
521        let _ = std::fs::remove_dir_all(&dir);
522    }
523
524    #[test]
525    fn the_file_rolls_over_and_keeps_the_newest() {
526        let dir = temp_dir("roll");
527        let mut file = RollingFile::new(dir.clone());
528        let line = vec![b'x'; (MAX_FILE_BYTES / 2) as usize];
529        let now = Instant::now();
530        // Two lines fill a file; each third starts the next one.
531        for n in 0..(2 * (KEPT_FILES + 2)) {
532            let mut line = line.clone();
533            line[0] = b'0' + n as u8;
534            file.write(&line, now);
535        }
536        for n in 1..=KEPT_FILES {
537            let older = std::fs::metadata(dir.join(format!("app.{n}.log"))).unwrap();
538            assert_eq!(older.len(), line.len() as u64 * 2);
539        }
540        assert!(!dir.join(format!("app.{}.log", KEPT_FILES + 1)).exists());
541        let newest = std::fs::read(dir.join("app.log")).unwrap();
542        assert_eq!(newest.len(), line.len() * 2);
543        assert_eq!(newest[0], b'0' + (2 * (KEPT_FILES + 1)) as u8);
544        let _ = std::fs::remove_dir_all(&dir);
545    }
546
547    #[test]
548    fn a_file_that_cannot_be_written_is_tried_again_later() {
549        let dir = temp_dir("blocked");
550        // A file where the directory should be.
551        std::fs::write(&dir, b"").unwrap();
552        let mut file = RollingFile::new(dir.join("logs"));
553        let now = Instant::now();
554        file.write(b"lost\n", now);
555        assert_eq!(file.retry_at, Some(now + RETRY_AFTER));
556        std::fs::remove_file(&dir).unwrap();
557        file.write(b"still waiting\n", now + RETRY_AFTER / 2);
558        assert!(!dir.join("logs/app.log").exists());
559        file.write(b"back\n", now + RETRY_AFTER);
560        assert_eq!(
561            std::fs::read_to_string(dir.join("logs/app.log")).unwrap(),
562            "back\n"
563        );
564        let _ = std::fs::remove_dir_all(&dir);
565    }
566
567    #[test]
568    fn panics_are_described_as_rust_prints_them() {
569        let location = std::panic::Location::caller();
570        let at = format!(
571            "{}:{}:{}",
572            location.file(),
573            location.line(),
574            location.column()
575        );
576        let payload: Box<dyn std::any::Any + Send> = Box::new("index out of bounds");
577        assert_eq!(
578            panic_text(Some("nsh-engine"), Some(location), payload.as_ref()),
579            format!("thread 'nsh-engine' panicked at {at}:\nindex out of bounds")
580        );
581        let payload: Box<dyn std::any::Any + Send> = Box::new(String::from("no window"));
582        assert_eq!(
583            panic_text(None, None, payload.as_ref()),
584            "thread '<unnamed>' panicked:\nno window"
585        );
586        let payload: Box<dyn std::any::Any + Send> = Box::new(7_u8);
587        assert_eq!(
588            panic_text(Some("main"), None, payload.as_ref()),
589            "thread 'main' panicked:\nBox<dyn Any>"
590        );
591    }
592
593    #[test]
594    fn panics_reach_the_file_whatever_the_filter() {
595        let dir = temp_dir("panic");
596        // A filter that logs only another crate's lines.
597        let logger: &'static Logger = Box::leak(Box::new(Logger::new(
598            LogOptions {
599                directory: Some(dir.clone()),
600                ..LogOptions::default()
601            },
602            Some("my_app=debug"),
603        )));
604        let previous: Arc<PanicHook> = Arc::from(std::panic::take_hook());
605        let chained = Arc::new(Mutex::new(0));
606        let hook = {
607            let (previous, chained) = (previous.clone(), chained.clone());
608            Box::new(move |info: &std::panic::PanicHookInfo<'_>| {
609                if info.payload().downcast_ref::<&str>() == Some(&"the logged panic") {
610                    *chained.lock().unwrap() += 1;
611                }
612                previous(info);
613            })
614        };
615        std::panic::set_hook(log_panics(logger, hook));
616        let caught = std::panic::catch_unwind(|| panic!("the logged panic"));
617        // Other tests' panics keep the hook they had.
618        std::panic::set_hook(Box::new(move |info| previous(info)));
619        assert!(caught.is_err());
620        assert_eq!(*chained.lock().unwrap(), 1, "the previous hook runs too");
621        let text = std::fs::read_to_string(dir.join("app.log")).unwrap();
622        // Other tests panicking meanwhile may add their lines too.
623        let lines: Vec<&str> = text.lines().collect();
624        let at = lines
625            .iter()
626            .position(|line| *line == "the logged panic")
627            .expect(&text);
628        let head = lines[at - 1];
629        assert!(head.contains(" ERROR panic: thread '"), "{text}");
630        assert!(
631            head.contains("panics_reach_the_file_whatever_the_filter"),
632            "{text}"
633        );
634        assert!(
635            head.contains("' panicked at ") && head.contains("logging.rs:"),
636            "{text}"
637        );
638        let _ = std::fs::remove_dir_all(&dir);
639    }
640
641    #[test]
642    fn the_log_directory_is_in_the_apps_data_directory() {
643        let Some(data) = crate::support_dir() else {
644            return;
645        };
646        assert_eq!(
647            log_dir("com.example.notes"),
648            Some(data.join("com.example.notes/logs"))
649        );
650        assert_eq!(log_dir("../x"), Some(data.join("default/logs")));
651    }
652
653    #[test]
654    fn the_log_directory_option_comes_first() {
655        let data = Path::new("/data");
656        let logs = Path::new("/logs/ui");
657        assert_eq!(
658            log_directory("com.example.notes", Some(data), Some(logs)),
659            Some(logs.to_path_buf())
660        );
661        assert_eq!(
662            log_directory("com.example.notes", None, Some(logs)),
663            Some(logs.to_path_buf())
664        );
665    }
666
667    #[test]
668    fn without_a_log_directory_option_the_data_directory_holds_the_logs() {
669        assert_eq!(
670            log_directory("com.example.notes", Some(Path::new("/data")), None),
671            Some(PathBuf::from("/data/logs"))
672        );
673        assert_eq!(
674            log_directory("com.example.notes", None, None),
675            log_dir("com.example.notes")
676        );
677    }
678
679    #[test]
680    fn a_log_directory_option_gets_the_files_and_the_data_directory_none() {
681        let root = temp_dir("log-dir-option");
682        let (data, logs) = (root.join("data"), root.join("logs/ui"));
683        let directory = log_directory("a.b", Some(&data), Some(&logs)).unwrap();
684        let logger = Logger::new(
685            LogOptions {
686                directory: Some(directory),
687                ..LogOptions::default()
688            },
689            Some("info"),
690        );
691        log(&logger, Level::Info, "t", "hello");
692        assert!(
693            std::fs::read_to_string(logs.join("app.log"))
694                .unwrap()
695                .contains("hello")
696        );
697        assert!(!data.join("logs").exists());
698        let _ = std::fs::remove_dir_all(&root);
699    }
700
701    #[test]
702    fn timestamps_are_utc() {
703        let time = UNIX_EPOCH + Duration::from_millis(1_794_472_205_123);
704        assert_eq!(Timestamp(time).to_string(), "2026-11-12T08:30:05.123Z");
705        assert_eq!(
706            Timestamp(UNIX_EPOCH).to_string(),
707            "1970-01-01T00:00:00.000Z"
708        );
709        assert_eq!(civil_from_days(-1), (1969, 12, 31));
710        assert_eq!(civil_from_days(11_016), (2000, 2, 29));
711    }
712}