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