Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 8 additions & 6 deletions CONTRIBUTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -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/`.
Expand Down Expand Up @@ -80,9 +81,10 @@ machine's graphics card, which is smoother.

**What it leaves.** Captures go to `target/e2e/scenarios/<journey>/` (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
Expand Down
214 changes: 189 additions & 25 deletions crates/app/src/logging.rs
Original file line number Diff line number Diff line change
@@ -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`).
Expand Down Expand Up @@ -88,12 +89,11 @@ fn start_as(directory: &Path, build: Build) -> Option<LoggerHandle> {
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()
Expand All @@ -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<VecDeque<String>>,
}

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();
Expand All @@ -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() {
Expand Down Expand Up @@ -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]) {
Expand All @@ -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", &[]);

Expand All @@ -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", &[]);

Expand All @@ -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", &[]);
Expand All @@ -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", &[]);

Expand All @@ -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")]);
Expand All @@ -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")]);
Expand All @@ -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<String> {
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();
Expand Down Expand Up @@ -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();
Expand All @@ -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}");
}
Expand Down
2 changes: 1 addition & 1 deletion docs/architecture/decisions.md
Original file line number Diff line number Diff line change
Expand Up @@ -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. |
Loading