diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 651e24ed..8c2305fb 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -26,6 +26,11 @@ cargo run -p app -- --profile ../devnotes-profile `--profile` keeps the run apart from an installed DevNotes: its libraries, logs and window 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). + 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/`. @@ -75,7 +80,9 @@ 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 and what it wrote in its terminal. CI keeps the same folder for each system. +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. **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 e694fe4f..14bbced2 100644 --- a/crates/app/src/logging.rs +++ b/crates/app/src/logging.rs @@ -1,35 +1,136 @@ -//! The log file, and what a panic leaves in it. +//! The log: what each build writes to the terminal and to the file (D35), and what a panic +//! leaves in it. +use std::io::Write; use std::panic::PanicHookInfo; use std::path::Path; use std::sync::OnceLock; use std::sync::atomic::{AtomicBool, Ordering}; -use flexi_logger::{Cleanup, Criterion, Duplicate, FileSpec, Logger, LoggerHandle, Naming}; +use flexi_logger::writers::FileLogWriter; +use flexi_logger::{ + Cleanup, Criterion, DeferredNow, Duplicate, FileSpec, LogSpecification, Logger, LoggerHandle, Naming, +}; +use log::{LevelFilter, Record}; + +/// Replaces the levels for one run, in any build, in `flexi_logger`'s syntax +/// (`engine=trace,ui::backend=debug`). +pub(crate) const LEVELS: &str = "DEVNOTES_LOG"; + +/// Our crates, this binary's own included: every other one stays at `warn`. +const OURS: [&str; 8] = + [env!("CARGO_CRATE_NAME"), "ui", "engine", "platform", "text", "richtext", "drawing", "i18n"]; + +/// Two dependencies log an error they also return, which our own line already says: left out, or +/// the log would read each failure twice. +const ECHOES: [&str; 2] = ["cargo_packager_updater", "eframe::native::run"]; + +/// Which build runs: each has its levels, its terminal and its file (D35). +#[derive(Clone, Copy)] +enum Build { + Debug, + Release, + E2e, +} -/// What is written, from `info` up. Two dependencies log an error they also return, which our -/// own line already says: left out, or the terminal would read each failure twice. -const WRITTEN: &str = "info, cargo_packager_updater = off, eframe::native::run = off"; +impl Build { + const RUNNING: Self = if cfg!(feature = "e2e") { + Self::E2e + } else if cfg!(debug_assertions) { + Self::Debug + } else { + Self::Release + }; + + fn ours(self) -> LevelFilter { + match self { + Self::Debug | Self::E2e => LevelFilter::Debug, + Self::Release => LevelFilter::Info, + } + } + + /// The e2e flavour's terminal is a file the driver keeps beside a failed journey, with its + /// log: errors alone, as before, so that nothing it writes reads twice. + fn terminal(self) -> Duplicate { + match self { + Self::Debug | Self::Release => Duplicate::All, + Self::E2e => Duplicate::Error, + } + } + + /// The file a person sends us holds warnings and errors; the e2e flavour's, kept beside a + /// failed journey, holds all the levels let through. + fn file(self) -> LevelFilter { + match self { + Self::Debug | Self::Release => LevelFilter::Warn, + Self::E2e => LevelFilter::Trace, + } + } +} /// Kept by `main` until the end: dropping the handle stops the logger. `None` when the -/// directory cannot be written, and the application runs without a log. Errors alone reach the -/// terminal: a warning there reads as a fault, and the user can do nothing about it. +/// directory cannot be written, and the application runs without a log. pub(crate) fn start(directory: &Path) -> Option { + start_as(directory, Build::RUNNING) +} + +fn start_as(directory: &Path, build: Build) -> Option { + let asked = std::env::var_os(LEVELS).map(|asked| asked.to_str().map(LogSpecification::parse)); + let unreadable = matches!(asked, Some(None | Some(Err(_)))); + let levels = match asked { + Some(Some(Ok(levels))) => levels, + _ => levels(build), + }; let file = FileSpec::default() .directory(directory) .basename("devnotes") .suppress_timestamp(); - Logger::try_with_str(WRITTEN) - .and_then(|logger| { - logger - .log_to_file(file) - .append() - .rotate(Criterion::Size(5_000_000), Naming::Numbers, Cleanup::KeepLogFiles(3)) - .duplicate_to_stderr(Duplicate::Error) + let handle = FileLogWriter::builder(file) + .append() + .rotate(Criterion::Size(5_000_000), Naming::Numbers, Cleanup::KeepLogFiles(3)) + .max_level(build.file()) + .format(line) + .try_build() + .and_then(|file| { + Logger::with(levels.clone()) + .log_to_writer(Box::new(file)) + .duplicate_to_stderr(build.terminal()) + .format_for_stderr(line) .start() }) .inspect_err(|error| eprintln!("devnotes: no log file: {error}")) - .ok() + .ok()?; + if unreadable { + log::warn!("{LEVELS} is no log specification: the levels of the build apply"); + } + log::debug!("Logging at {levels}"); + Some(handle) +} + +fn levels(build: Build) -> LogSpecification { + let mut levels = LogSpecification::builder(); + levels.default(LevelFilter::Warn); + for ours in OURS { + levels.module(ours, build.ours()); + } + for echo in ECHOES { + levels.module(echo, LevelFilter::Off); + } + levels.build() +} + +/// 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(); + write!( + out, + "{} {:<5} [{}] {}: {}", + now.format("%Y-%m-%d %H:%M:%S%.3f"), + record.level(), + thread.name().unwrap_or("unnamed"), + record.target(), + record.args() + ) } /// What a process that panicked exits with, as Rust's own runtime does. @@ -122,46 +223,137 @@ mod tests { assert!(written.contains("a line the test looks for"), "{written}"); } - /// Where the process whose terminal the test below reads writes its log. - const TERMINAL_IN: &str = "DEVNOTES_TEST_TERMINAL_IN"; + /// Set, the test is the process run apart, and writes its log in that directory. + const APART: &str = "DEVNOTES_TEST_APART"; - /// Run again as a process of its own: its stderr is the terminal a person reads. - #[test] - fn only_errors_reach_the_terminal_and_a_dependency_s_echo_not_at_all() { - if let Some(directory) = std::env::var_os(TERMINAL_IN) { - let _logger = start(Path::new(&directory)); - log::info!("an info line"); - log::warn!("a warning line"); - log::error!("an error line"); - 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); - } + /// Runs `test` again as a process of its own, `set` in its environment: its stderr is the + /// terminal a person reads, and its file is read back. + fn apart(test: &str, set: &[(&str, &str)]) -> (String, String) { let directory = tempfile::tempdir().unwrap(); - let ended = std::process::Command::new(std::env::current_exe().unwrap()) - .args([ - "--exact", - "logging::tests::only_errors_reach_the_terminal_and_a_dependency_s_echo_not_at_all", - ]) - .env(TERMINAL_IN, directory.path()) + .args(["--exact", &format!("logging::tests::{test}")]) + .env(APART, directory.path()) + .env_remove(LEVELS) + .envs(set.iter().copied()) .output() .unwrap(); - assert!(ended.status.success(), "{ended:?}"); - let terminal = String::from_utf8_lossy(&ended.stderr); - assert!(terminal.contains("an error line"), "{terminal}"); - for quiet in ["an info line", "a warning line", "echo"] { - assert!(!terminal.contains(quiet), "{quiet} in {terminal}"); - } - let written: String = std::fs::read_dir(directory.path()) + let file = std::fs::read_dir(directory.path()) .unwrap() .map(|entry| std::fs::read_to_string(entry.unwrap().path()).unwrap()) .collect(); - assert!(written.contains("an info line"), "{written}"); - assert!(written.contains("a warning line"), "{written}"); - assert!(!written.contains("echo"), "{written}"); + (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) { + 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"); + 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); + } + + fn holds(output: &str, lines: &[&str]) { + for line in lines { + assert!(output.contains(line), "{line} not in {output}"); + } + } + + fn lacks(output: &str, lines: &[&str]) { + for line in lines { + assert!(!output.contains(line), "{line} in {output}"); + } + } + + const WARNINGS_AND_ERRORS: [&str; 3] = ["a warning line", "an error line", "a dependency's warning"]; + + #[test] + fn a_debug_build_shows_debug_lines_and_files_warnings_alone() { + when_apart(Build::Debug); + + let (terminal, file) = apart("a_debug_build_shows_debug_lines_and_files_warnings_alone", &[]); + + holds(&terminal, &["a debug line", "an info line"]); + holds(&terminal, &WARNINGS_AND_ERRORS); + lacks(&terminal, &["a trace line", "a dependency's info", "echo"]); + holds(&file, &WARNINGS_AND_ERRORS); + lacks(&file, &["a debug line", "an info line", "a dependency's info", "echo"]); + } + + #[test] + fn a_release_shows_info_lines_never_debug_and_files_warnings_alone() { + when_apart(Build::Release); + + let (terminal, file) = apart("a_release_shows_info_lines_never_debug_and_files_warnings_alone", &[]); + + holds(&terminal, &["an info line"]); + holds(&terminal, &WARNINGS_AND_ERRORS); + lacks(&terminal, &["a trace line", "a debug line", "a dependency's info", "echo"]); + holds(&file, &WARNINGS_AND_ERRORS); + lacks(&file, &["a debug line", "an info line", "a dependency's info", "echo"]); + } + + #[test] + fn the_e2e_flavour_files_debug_lines_and_keeps_its_terminal_to_errors() { + when_apart(Build::E2e); + + let (terminal, file) = + apart("the_e2e_flavour_files_debug_lines_and_keeps_its_terminal_to_errors", &[]); + + holds(&terminal, &["an error line"]); + lacks(&terminal, &["a debug line", "an info line", "a warning line", "echo"]); + holds(&file, &["a debug line", "an info line"]); + holds(&file, &WARNINGS_AND_ERRORS); + lacks(&file, &["a trace line", "a dependency's info", "echo"]); + } + + #[test] + fn a_line_reads_time_level_thread_target_and_message() { + when_apart(Build::Debug); + + let (terminal, file) = apart("a_line_reads_time_level_thread_target_and_message", &[]); + + for output in [terminal, file] { + let line = output.lines().find(|line| line.contains("a warning line")).unwrap(); + let (time, rest) = line.split_at(23); + assert!(time.chars().all(|c| c.is_ascii_digit() || "-: .".contains(c)), "{line}"); + assert_eq!(time.as_bytes()[19], b'.', "milliseconds: {line}"); + assert!(rest.starts_with(" WARN ["), "{line}"); + assert!(rest.ends_with("] platform::tray: a warning line"), "{line}"); + } + } + + #[test] + fn the_variable_replaces_the_levels_for_one_run() { + when_apart(Build::Release); + + let (terminal, _) = + apart("the_variable_replaces_the_levels_for_one_run", &[(LEVELS, "engine=trace")]); + + holds(&terminal, &["a trace line", "a debug line", "an error line"]); + lacks(&terminal, &["an info line", "a warning line", "a dependency's"]); + } + + #[test] + fn an_unreadable_variable_is_ignored_with_one_line_saying_so() { + when_apart(Build::Debug); + + let (terminal, file) = + apart("an_unreadable_variable_is_ignored_with_one_line_saying_so", &[(LEVELS, "engine=loud")]); + + holds(&terminal, &["a debug line", "DEVNOTES_LOG is no log specification"]); + holds(&file, &["DEVNOTES_LOG is no log specification"]); + lacks(&terminal, &["loud"]); } #[test] diff --git a/docs/architecture/README.md b/docs/architecture/README.md index 234c42d7..25abce70 100644 --- a/docs/architecture/README.md +++ b/docs/architecture/README.md @@ -24,6 +24,7 @@ For build/run instructions see [CONTRIBUTING](../../CONTRIBUTING.md). | [The core](engine.md) | the engine and its binary, the notes index, persistence, the shared services | the engine, the schema, the index | | [Language, accessibility and theming](i18n-accessibility-theming.md) | translations, the accessibility floor, the theme tokens | a string, a colour, a size | | [Updates and releases](releasing.md) | the updater, the release workflow, the release binary, how far back an upgrade reaches | a release, a package, the updater | +| [Logs](logs.md) | the three outputs and their levels, what a line may say, `DEVNOTES_LOG` | a log line, a level | | [Testing](testing.md) | benchmarks and their figures, the Rust tests, the interface tests, the journeys | a test, a benchmark | | [The website](website.md) | devnotes.fr, its pages and how it is published | the site | diff --git a/docs/architecture/decisions.md b/docs/architecture/decisions.md index 891cfa88..969905ab 100644 --- a/docs/architecture/decisions.md +++ b/docs/architecture/decisions.md @@ -37,3 +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. | diff --git a/docs/architecture/engine.md b/docs/architecture/engine.md index a7078b33..2493d63d 100644 --- a/docs/architecture/engine.md +++ b/docs/architecture/engine.md @@ -44,11 +44,9 @@ unwinding tables, and `exit` before the abort keeps the open library's memory ou system's crash reports. A second panic, in the dialog, exits at once. No thread is an exception: the tray of Linux opens no library at run time any more (D29). -The log (`flexi_logger`, `devnotes.log`, three files of 5 MB) starts before the window. It -writes from `info` up; **only errors reach the terminal**: a warning there reads as a fault the -user can do nothing about, and stays in the file. Two dependencies log an error they also return -(`cargo_packager_updater`, `eframe::native::run`), which our own line already says: their targets -are left out of the log, never a whole level. What libraries write themselves on stderr (Mesa, +The log (`flexi_logger`, `devnotes.log`, three files of 5 MB) starts before the window: the +terminal from `debug` in a debug build and from `info` in a release, the file warnings and errors +alone (D35, → "The three outputs"). What libraries write themselves on stderr (Mesa, libxkbcommon, GTK) goes around the log, and is fixed where it comes from. Then the input channel and its `Waker` are made, and eframe opens the window **hidden** at the geometry `platform::window` read back (size, place, maximised; never whether it was visible), with eframe's persistence off: it would write egui's diff --git a/docs/architecture/logs.md b/docs/architecture/logs.md new file mode 100644 index 00000000..ee78ff80 --- /dev/null +++ b/docs/architecture/logs.md @@ -0,0 +1,53 @@ +# Logs + +What the application writes about itself, where, at which level, and what a line may say (D35). [Home](README.md) + +## The three outputs + +`crates/app/src/logging.rs` starts the log before the window (→ "The binary, its profile and its +window"): one `flexi_logger`, a terminal and a file, each at its own level. + +| Build | Terminal | File (`devnotes.log`) | +| ------------------ | ----------------------- | ----------------------- | +| debug | our crates from `debug` | `warn` and `error` | +| release | our crates from `info` | `warn` and `error` | +| the `e2e` flavour | `error` alone | our crates from `debug` | + +Our crates are the workspace's: the binary's own (`devnotes`), `ui`, `engine`, `platform`, `text`, +`richtext`, `drawing` and `i18n`. Every other crate stays at `warn` in every build: its `debug` +may hold a path or a URL, and its `info` is not ours to read. Two dependencies log an error they +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, +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 +nothing, and its log holds every level our crates write, for a failure to show what led to it. + +Each line, on both outputs: local time to the millisecond, level, thread, target, message. + +```text +2026-12-04 10:12:03.412 WARN [main] ui::services::errors: errors.noteGone: NoteNotFound: … +``` + +## What a line may say + +Names, codes, ids and durations; never what a person typed or wrote, a passphrase or a key +(D18). An error goes through `AppError::for_log`: its code, and its detail only where nothing typed +is in it. A panic is logged by its place and its thread, never its message. ⚠️ Never `{:?}` of a +value that carries content: a derived `Debug` prints the payload, a checklist's items or a request's +URL. + +## Changing the levels for one run + +`DEVNOTES_LOG`, in `flexi_logger`'s syntax, replaces the levels for one run, in any build: + +```bash +DEVNOTES_LOG=engine=trace,ui::backend=debug cargo run -p app -- --profile ../devnotes-profile +``` + +What it names is all that logs: the floor of the other crates goes with it, unless it says one +(`warn,engine=trace`). An unreadable value is ignored, and one warning says so. The first `debug` +line of a run says the levels it logs at. diff --git a/docs/architecture/testing.md b/docs/architecture/testing.md index 3f93603b..a1c14ec7 100644 --- a/docs/architecture/testing.md +++ b/docs/architecture/testing.md @@ -368,7 +368,8 @@ takes a press of any length for a click (`app::pointer`): the system's pointer m the two, or a frame of a busy runner outlasting egui's 0.8 s, would make the click a drag. `App::relaunch` asks `--action quit`, waits for the process to end its queue drained, and starts it again on the same profile. The journeys' requests go to a server of the suite's own (`server.rs`), never to the network. A failed journey leaves its -last screen and the application's log in `target/e2e/scenarios//`, beside its captures. +last screen and the application's log, from `debug` up (→ "The three outputs"), in +`target/e2e/scenarios//`, beside its captures. | Journey | What is walked | | --------------------------------- | --------------------------------------------------------------------------- | diff --git a/e2e/src/sdk/disk.rs b/e2e/src/sdk/disk.rs index 2d20bc02..e3161b43 100644 --- a/e2e/src/sdk/disk.rs +++ b/e2e/src/sdk/disk.rs @@ -41,6 +41,18 @@ impl Disk<'_> { .any(|file| std::fs::read(file).is_ok_and(|bytes| says_word(&profile, file, &bytes, word))) }); } + + /// The log holds lines below a warning: the e2e flavour files every level its build lets + /// through, so that a failed journey leaves what led to it. + pub fn expect_debug_in_log(&mut self, says: &str) { + let logs = self.0.profile().join("logs"); + self.0.until(says, |_| { + let files = files_under(&logs).unwrap_or_default(); + files + .iter() + .any(|file| std::fs::read_to_string(file).is_ok_and(|log| log.contains(" DEBUG ["))) + }); + } } /// Whether a file says a word, in its bytes or in its path under the profile. diff --git a/e2e/tests/01_first_day.rs b/e2e/tests/01_first_day.rs index a6c45fd4..2083fb63 100644 --- a/e2e/tests/01_first_day.rs +++ b/e2e/tests/01_first_day.rs @@ -22,6 +22,7 @@ fn making_the_library(app: &mut App) { step("the first launch asks to protect the library, and says nothing in the terminal", || { app.expect(|s| s.gate().confirmation && !s.unlocked(), "the phrase is asked twice"); app.expect_silent_terminal("the launch wrote nothing in the terminal"); + app.disk().expect_debug_in_log("its log files what it does from debug up"); app.capture("gate"); });