From ee82b050cc03d34d445fe621fb62e4f5e0f7e6af Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 4 Dec 2026 19:15:45 +0000 Subject: [PATCH] Logs: the lines before a warning or a crash kept in the log file The file's writer is now one of ours, Kept, wrapping flexi_logger's: it keeps the last 200 lines of our crates below what the file keeps, the lines the terminal shows under the levels in force, and writes them into the file before the next warning, error or panic, under one line that says how many. A second warning brings only what came after the first. Lines are formatted as they come, time and thread included, and the file's writer writes them as they are; a dependency's lines are never kept. The e2e flavour, whose file keeps every level, keeps none. The panic hook needs no change: its error line brings the ring first. docs/security.md says what the file may hold; the wiki's logs page, D35 and CONTRIBUTING say it too. Closes #1845 Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01BbVs5tCyTr9AasGra3Zzg3 --- CONTRIBUTING.md | 14 ++- crates/app/src/logging.rs | 214 +++++++++++++++++++++++++++++---- docs/architecture/decisions.md | 2 +- docs/architecture/logs.md | 26 +++- docs/security.md | 2 +- 5 files changed, 223 insertions(+), 35 deletions(-) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 8c2305fb3..8227f66f7 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -27,9 +27,10 @@ cargo run -p app -- --profile ../devnotes-profile geometry all go in that directory. A debug build writes its log on the terminal from `debug` up, a release from `info`; the file under -the profile's `logs/` keeps warnings and errors. `DEVNOTES_LOG` changes the levels for one run, in -`flexi_logger`'s syntax (`DEVNOTES_LOG=engine=trace,ui::backend=debug cargo run -p app -- …`); what a -line may say is in [docs/architecture/logs.md](docs/architecture/logs.md). +the profile's `logs/` keeps warnings and errors, each after the lines that led to it. `DEVNOTES_LOG` +changes the levels for one run, in `flexi_logger`'s syntax +(`DEVNOTES_LOG=engine=trace,ui::backend=debug cargo run -p app -- …`); what a line may say is in +[docs/architecture/logs.md](docs/architecture/logs.md). Node.js 24 runs the release scripts, which have no dependency; nothing is installed at the root. The website has its own project in `website/`. @@ -80,9 +81,10 @@ machine's graphics card, which is smoother. **What it leaves.** Captures go to `target/e2e/scenarios//` (elsewhere with `DEVNOTES_E2E_OUTPUT`), and a failed journey leaves there its last screen (`failure.png`), the -application's log — every level from `debug`, where a person's keeps warnings alone — and what it -wrote in its terminal, errors alone. A journey that passes leaves neither, and the console of a -run shows the steps, never the application's log. CI keeps the same folder for each system. +application's log — every level from `debug`, where a person's keeps warnings and what led to them — +and what it wrote in its terminal, errors alone. A journey that passes leaves neither, and the +console of a run shows the steps, never the application's log. CI keeps the same folder for each +system. **When a change breaks a journey**, read the step that failed, then open its last screen and its log. Run that journey alone and watch it. Then mend the application; or the step, if what the person does diff --git a/crates/app/src/logging.rs b/crates/app/src/logging.rs index 14bbced2d..5076f81a4 100644 --- a/crates/app/src/logging.rs +++ b/crates/app/src/logging.rs @@ -1,17 +1,18 @@ //! The log: what each build writes to the terminal and to the file (D35), and what a panic //! leaves in it. +use std::collections::VecDeque; use std::io::Write; use std::panic::PanicHookInfo; use std::path::Path; -use std::sync::OnceLock; use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::{Mutex, OnceLock, PoisonError}; -use flexi_logger::writers::FileLogWriter; +use flexi_logger::writers::{FileLogWriter, LogWriter}; use flexi_logger::{ Cleanup, Criterion, DeferredNow, Duplicate, FileSpec, LogSpecification, Logger, LoggerHandle, Naming, }; -use log::{LevelFilter, Record}; +use log::{Level, LevelFilter, Record}; /// Replaces the levels for one run, in any build, in `flexi_logger`'s syntax /// (`engine=trace,ui::backend=debug`). @@ -88,12 +89,11 @@ fn start_as(directory: &Path, build: Build) -> Option { let handle = FileLogWriter::builder(file) .append() .rotate(Criterion::Size(5_000_000), Naming::Numbers, Cleanup::KeepLogFiles(3)) - .max_level(build.file()) - .format(line) + .format(verbatim) .try_build() .and_then(|file| { Logger::with(levels.clone()) - .log_to_writer(Box::new(file)) + .log_to_writer(Box::new(Kept::new(file, build.file()))) .duplicate_to_stderr(build.terminal()) .format_for_stderr(line) .start() @@ -119,6 +119,87 @@ fn levels(build: Build) -> LogSpecification { levels.build() } +/// Whether `target` is one of our crates, or a module of one. +fn ours(target: &str) -> bool { + OURS.iter().any(|ours| { + target + .strip_prefix(ours) + .is_some_and(|rest| rest.is_empty() || rest.starts_with("::")) + }) +} + +/// The lines below what the file keeps, the last ones at most, written before the next warning. +const BEFORE: usize = 200; + +/// The file, and the last lines below what it keeps: a warning, an error or a panic is filed after +/// the lines that led to it, under one line that says so, and the next one after those that came +/// since. Our crates' lines alone: a dependency's `debug` may hold a path or a URL. +struct Kept { + file: FileLogWriter, + keeps: LevelFilter, + before: Mutex>, +} + +impl Kept { + fn new(file: FileLogWriter, keeps: LevelFilter) -> Self { + Self { file, keeps, before: Mutex::new(VecDeque::with_capacity(BEFORE)) } + } + + /// The file's writer writes what it is handed: the lines are formatted as they come. + fn write_line(&self, now: &mut DeferredNow, text: &str) -> std::io::Result<()> { + self.file.write(now, &Record::builder().args(format_args!("{text}")).build()) + } +} + +impl LogWriter for Kept { + fn write(&self, now: &mut DeferredNow, record: &Record<'_>) -> std::io::Result<()> { + let below = record.level() > self.keeps; + if below && !ours(record.target()) { + return Ok(()); + } + let mut text = Vec::new(); + line(&mut text, now, record)?; + let text = String::from_utf8_lossy(&text).into_owned(); + // Held until written: another thread's lines come before or after these, never between. + let mut before = self.before.lock().unwrap_or_else(PoisonError::into_inner); + if below { + if before.len() == BEFORE { + before.pop_front(); + } + before.push_back(text); + return Ok(()); + } + if record.level() <= Level::Warn && !before.is_empty() { + self.write_line(now, &leading(before.len()))?; + for kept in before.drain(..) { + self.write_line(now, &kept)?; + } + } + self.write_line(now, &text) + } + + fn flush(&self) -> std::io::Result<()> { + self.file.flush() + } + + fn shutdown(&self) { + self.file.shutdown(); + } +} + +fn leading(count: usize) -> String { + if count == 1 { + "— the line before —".to_owned() + } else { + format!("— the {count} lines before —") + } +} + +/// What the file's writer is handed, a line already formatted. +fn verbatim(out: &mut dyn Write, _: &mut DeferredNow, record: &Record<'_>) -> std::io::Result<()> { + write!(out, "{}", record.args()) +} + /// One line, on the terminal and in the file alike. fn line(out: &mut dyn Write, now: &mut DeferredNow, record: &Record<'_>) -> std::io::Result<()> { let thread = std::thread::current(); @@ -140,9 +221,10 @@ const PANICKED: i32 = 101; static NOTICE: OnceLock<(String, String)> = OnceLock::new(); static STOPPING: AtomicBool = AtomicBool::new(false); -/// A panic ends the process, on whatever thread (D18): the place is logged, never the message -/// — a panic slicing a string quotes it, a note's text perhaps —, the person is told, and the -/// process exits. What was written is in SQLite's journal; the next open checks it (the gate). +/// A panic ends the process, on whatever thread (D18): the place is logged after the lines that +/// led to it, never the message — a panic slicing a string quotes it, a note's text perhaps —, the +/// person is told, and the process exits. What was written is in SQLite's journal; the next open +/// checks it (the gate). /// ⚠️ It leaves by `exit`: the abort that would follow hands the process, the open library in /// its memory, to the system's crash reports. pub(crate) fn install_panic_hook() { @@ -245,22 +327,28 @@ mod tests { (String::from_utf8_lossy(&ended.stderr).into_owned(), file) } - /// In the process run apart: the log started as `build`, a line at each level written, and - /// the process ended. - fn when_apart(build: Build) { + /// In the process run apart: the log started as `build`, `lines` written, and the process + /// ended. + fn when_apart(build: Build, lines: fn()) { let Some(directory) = std::env::var_os(APART) else { return }; let _logger = start_as(Path::new(&directory), build); - log::trace!(target: "engine::notes", "a trace line"); - log::debug!(target: "engine::notes", "a debug line"); - log::info!(target: "ui::state", "an info line"); + lines(); + log::logger().flush(); + std::process::exit(0); + } + + /// A line at each level. The lines below `warn` come after the last warning: a file that + /// keeps warnings alone never brings them. + fn every_level() { log::warn!(target: "platform::tray", "a warning line"); log::error!(target: "engine::db", "an error line"); - log::info!(target: "wgpu_core", "a dependency's info"); log::warn!(target: "wgpu_core", "a dependency's warning"); log::error!(target: "cargo_packager_updater", "the updater's echo"); log::error!(target: "eframe::native::run", "eframe's echo"); - log::logger().flush(); - std::process::exit(0); + log::trace!(target: "engine::notes", "a trace line"); + log::debug!(target: "engine::notes", "a debug line"); + log::info!(target: "ui::state", "an info line"); + log::info!(target: "wgpu_core", "a dependency's info"); } fn holds(output: &str, lines: &[&str]) { @@ -279,7 +367,7 @@ mod tests { #[test] fn a_debug_build_shows_debug_lines_and_files_warnings_alone() { - when_apart(Build::Debug); + when_apart(Build::Debug, every_level); let (terminal, file) = apart("a_debug_build_shows_debug_lines_and_files_warnings_alone", &[]); @@ -292,7 +380,7 @@ mod tests { #[test] fn a_release_shows_info_lines_never_debug_and_files_warnings_alone() { - when_apart(Build::Release); + when_apart(Build::Release, every_level); let (terminal, file) = apart("a_release_shows_info_lines_never_debug_and_files_warnings_alone", &[]); @@ -305,7 +393,7 @@ mod tests { #[test] fn the_e2e_flavour_files_debug_lines_and_keeps_its_terminal_to_errors() { - when_apart(Build::E2e); + when_apart(Build::E2e, every_level); let (terminal, file) = apart("the_e2e_flavour_files_debug_lines_and_keeps_its_terminal_to_errors", &[]); @@ -319,7 +407,7 @@ mod tests { #[test] fn a_line_reads_time_level_thread_target_and_message() { - when_apart(Build::Debug); + when_apart(Build::Debug, every_level); let (terminal, file) = apart("a_line_reads_time_level_thread_target_and_message", &[]); @@ -335,7 +423,7 @@ mod tests { #[test] fn the_variable_replaces_the_levels_for_one_run() { - when_apart(Build::Release); + when_apart(Build::Release, every_level); let (terminal, _) = apart("the_variable_replaces_the_levels_for_one_run", &[(LEVELS, "engine=trace")]); @@ -346,7 +434,7 @@ mod tests { #[test] fn an_unreadable_variable_is_ignored_with_one_line_saying_so() { - when_apart(Build::Debug); + when_apart(Build::Debug, every_level); let (terminal, file) = apart("an_unreadable_variable_is_ignored_with_one_line_saying_so", &[(LEVELS, "engine=loud")]); @@ -356,6 +444,80 @@ mod tests { lacks(&terminal, &["loud"]); } + /// The file's lines, from the first that holds `from`. + fn filed_from(file: &str, from: &str) -> Vec { + let lines = file.lines().skip_while(|line| !line.contains(from)); + lines.map(str::to_owned).collect() + } + + fn holds_in_order(filed: &[String], said: &[&str]) { + assert_eq!(filed.len(), said.len(), "{filed:#?}"); + for (line, says) in filed.iter().zip(said) { + assert!(line.contains(says), "{says} not in {line}"); + } + } + + #[test] + fn a_warning_is_filed_after_the_lines_that_led_to_it_and_the_next_after_those_since() { + when_apart(Build::Debug, || { + log::info!(target: "ui::action", "#1 Notes::OpenNote"); + log::debug!(target: "ui::backend", "db #1 notes::get 2 ms ok"); + log::warn!(target: "ui::services::errors", "the first warning"); + log::info!(target: "ui::action", "#2 Notes::Editor::Close"); + log::error!(target: "engine::db", "an error"); + log::info!(target: "ui::action", "#3 after the error"); + }); + + let (_, file) = + apart("a_warning_is_filed_after_the_lines_that_led_to_it_and_the_next_after_those_since", &[]); + + holds_in_order( + &filed_from(&file, "lines before"), + &[ + "— the 3 lines before —", + "devnotes::logging: Logging at", + "ui::action: #1 Notes::OpenNote", + "ui::backend: db #1 notes::get 2 ms ok", + "] ui::services::errors: the first warning", + "— the line before —", + "ui::action: #2 Notes::Editor::Close", + "] engine::db: an error", + ], + ); + } + + #[test] + fn the_last_two_hundred_lines_are_kept() { + when_apart(Build::Release, || { + for step in 1..=250 { + log::info!(target: "ui::state", "step {step:03}"); + } + log::warn!(target: "ui::state", "the warning"); + }); + + let (_, file) = apart("the_last_two_hundred_lines_are_kept", &[]); + + let filed = filed_from(&file, "lines before"); + assert_eq!(filed.first().map(String::as_str), Some("— the 200 lines before —"), "{file}"); + assert!(filed[1].ends_with("step 051") && filed[200].ends_with("step 250"), "{file}"); + lacks(&file, &["step 050"]); + } + + #[test] + fn a_dependency_line_is_never_kept_for_the_file() { + when_apart(Build::Debug, || { + log::debug!(target: "wgpu_core", "a dependency's debug"); + log::debug!(target: "engine::notes", "a debug line"); + log::warn!(target: "engine::notes", "a warning line"); + }); + + let (terminal, file) = apart("a_dependency_line_is_never_kept_for_the_file", &[(LEVELS, "debug")]); + + holds(&terminal, &["a dependency's debug"]); + holds(&file, &["a debug line", "a warning line"]); + lacks(&file, &["a dependency's debug"]); + } + #[test] fn a_failing_operation_is_logged_without_the_text_of_the_note() { logger(); @@ -458,6 +620,7 @@ mod tests { if let Some(directory) = std::env::var_os(PANIC_IN) { let _logger = start(Path::new(&directory)); install_panic_hook(); + log::info!(target: "ui::action", "#7 Notes::Delete"); panic!("psql -h prod -W hunter2"); } let directory = tempfile::tempdir().unwrap(); @@ -475,7 +638,8 @@ mod tests { .unwrap() .map(|entry| std::fs::read_to_string(entry.unwrap().path()).unwrap()) .collect(); - assert!(written.contains("Panicked at"), "{written}"); + let filed = filed_from(&written, "Notes::Delete"); + assert!(filed.len() == 2 && filed[1].contains("Panicked at"), "the lines before it: {written}"); assert!(written.contains("logging.rs"), "{written}"); assert!(!written.contains("hunter2"), "{written}"); } diff --git a/docs/architecture/decisions.md b/docs/architecture/decisions.md index 969905ab7..59bda7214 100644 --- a/docs/architecture/decisions.md +++ b/docs/architecture/decisions.md @@ -37,4 +37,4 @@ in the code. | D32 | The Angular application | Out of the tree since 1.0.0; the `angular-reference` tag and its pre-release keep all of it. Where egui differs from it by decision rather than by limit, egui is right. | | D33 | Workspace manifest | Each dependency declared once, version and common features, in the root `[workspace.dependencies]`; a crate takes `workspace = true` and adds only its own features. | | D34 | Title bar | The application's own on every system: no decorations from the system, minimise, maximise and close at the bar's right end; macOS keeps its three buttons, at the left end. Moving and resizing are the system's (`StartDrag`, `BeginResize`). No way back to the system's bar. | -| D35 | Logs | Terminal: our crates from `debug` in a debug build, from `info` in a release. File: `warn` and `error` alone. The e2e flavour files from `debug`, its terminal errors alone. Other crates at `warn`. A line says names, codes, ids and durations, never content (D18). `DEVNOTES_LOG` replaces the levels for one run. | +| D35 | Logs | Terminal: our crates from `debug` in a debug build, from `info` in a release. File: `warn` and `error`, after our last 200 lines. The e2e flavour files from `debug`, its terminal errors alone. Other crates at `warn`. A line says names, codes, ids, durations, never content (D18). `DEVNOTES_LOG` replaces the levels for one run. | diff --git a/docs/architecture/logs.md b/docs/architecture/logs.md index 0ef846bcf..435c6b70a 100644 --- a/docs/architecture/logs.md +++ b/docs/architecture/logs.md @@ -19,8 +19,8 @@ may hold a path or a URL, and its `info` is not ours to read. Two dependencies l also return (`cargo_packager_updater`, `eframe::native::run`), which our own line already says: their targets are off, never a whole level. -**The file is what a person sends us**: warnings and errors alone, three files of 5 MB at most, -under the profile's `logs/`. **A release's terminal** is whoever launched it from a shell (Linux, +**The file is what a person sends us**: warnings and errors, each after the lines that led to it +(→ "The lines before a warning"), three files of 5 MB at most, under the profile's `logs/`. **A release's terminal** is whoever launched it from a shell (Linux, macOS); a Windows release has none. **The e2e flavour's terminal is a file too**, the driver's, kept with the log beside a failed journey (`target/e2e/scenarios//`): it stays to errors, so that the first journey's « nothing in the terminal » holds and the console of a run says @@ -83,6 +83,28 @@ service function that fails says nothing more. A session thus reads as an action No call is a warning for its duration alone: a large library makes the slowest ones slow on every call, and a list of exceptions would be one more thing to keep. +## The lines before a warning + +A warning alone says what failed, not what led to it, and a release's terminal is seen by no one. +`Kept`, the file's writer in `logging.rs`, keeps the last 200 lines below what the file keeps, of +our crates alone (a dependency's `debug` may hold a path or a URL): the lines the terminal shows +under the levels in force, the actions in a release, the calls too in a debug build. A warning or +an error writes them into the file first, then itself, and empties them: + +```text +— the 3 lines before — +2026-12-04 10:12:04.207 INFO [main] ui::action: #411 Notes::ClearSearch +2026-12-04 10:12:05.031 INFO [main] ui::action: #412 Notes::OpenNote +2026-12-04 10:12:05.033 DEBUG [db] ui::backend: db #412 notes::get 1 ms NoteNotFound +2026-12-04 10:12:05.040 WARN [main] ui::services::errors: errors.noteGone: NoteNotFound: … +``` + +A second warning brings only what came after the first. A panic is an error line too: the hook +logs its place after the lines before it, then flushes (D18). The lines are formatted as they come, +time and thread included, and the file's writer writes them as they are. They say what a line may +say, so changing or closing a library leaves them; the e2e flavour, whose file keeps every level, +keeps none. + ## Changing the levels for one run `DEVNOTES_LOG`, in `flexi_logger`'s syntax, replaces the levels for one run, in any build: diff --git a/docs/security.md b/docs/security.md index edbb558e7..a1e9c42e9 100644 --- a/docs/security.md +++ b/docs/security.md @@ -50,7 +50,7 @@ Opening an attachment writes a decrypted copy inside your own profile, never the ### What the application itself guarantees - **One process per profile.** A second launch on the same profile hands over to the first and exits: the index assumes it is the only writer of the library, and two writers would leave it silently wrong. -- **No note in the logs.** The log (`devnotes.log`, under `%LOCALAPPDATA%\com.devnotes.app\logs` or `~/.local/share/com.devnotes.app/logs`) records what happened, never what you wrote: a crash records where and on which thread, **never its message**, since a message can quote a piece of a note. Neither is a passphrase or a key ever logged. +- **No note in the logs.** The log (`devnotes.log`, under `%LOCALAPPDATA%\com.devnotes.app\logs` or `~/.local/share/com.devnotes.app/logs`) records what happened, never what you wrote: a crash records where and on which thread, **never its message**, since a message can quote a piece of a note. Neither is a passphrase or a key ever logged. It keeps warnings and errors, each after the last lines that led to it: the names of the actions you took, the calls the window made, their duration and an error's code, never a title, a body, a field's value or a URL. Nothing sealed in the library is ever in it, and changing or closing a library leaves those lines as they are. - **No web page inside.** Since 1.0.0 the interface is native: there is no WebView, so no page, no script and no content policy to get wrong. A link in a note opens in your browser only if it is `http` or `https`; a `file:` link is a program to run, and is refused. - **A request script runs with your rights.** The script host is DevNotes itself, started again: every send and every file a script asks for goes through the application, which asks where it should, but the host's isolation rests on the script engine alone, not on a sandbox of the operating system. Run only scripts you would run yourself. - **No file sent behind your back.** A request script that gives a request a file to send, or sends one itself, stops the send and names the file; it leaves only after your yes, for that file alone. A collection run sends no such file. No file over 64 MB is read for a send.