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
9 changes: 8 additions & 1 deletion CONTRIBUTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -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/`.

Expand Down Expand Up @@ -75,7 +80,9 @@ 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 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
Expand Down
284 changes: 238 additions & 46 deletions crates/app/src/logging.rs
Original file line number Diff line number Diff line change
@@ -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<LoggerHandle> {
start_as(directory, Build::RUNNING)
}

fn start_as(directory: &Path, build: Build) -> Option<LoggerHandle> {
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.
Expand Down Expand Up @@ -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]
Expand Down
1 change: 1 addition & 0 deletions docs/architecture/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 |

Expand Down
1 change: 1 addition & 0 deletions docs/architecture/decisions.md
Original file line number Diff line number Diff line change
Expand Up @@ -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. |
8 changes: 3 additions & 5 deletions docs/architecture/engine.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
Loading