app: read the log the daemon actually writes

The daemon rolls its log at midnight and keeps the --log-file path as a
stem, so it writes logs/daemon.YYYY-MM-DD.log. Reload log read the
literal logs/daemon.log, a path that never exists, so every press failed
with a missing file, and the Log file row named the same path.

Read the newest daily file instead and show that path. Strip the ANSI
colours from what is read too: the file layer had colour on, so lines
already on disk carry escapes the box would draw as noise. record-daemon
writes the file without colour from here on.
This commit is contained in:
vhaudiquet committed 2026-11-24 00:16:08 +01:00
1 parent 85b6602b31
commit 42ba0ce882
2 files changed
+110 -10

No files matched your search

+105 -9
View File
@@ -34,11 +34,20 @@ pub fn recordings_dir() -> PathBuf {
.unwrap_or_else(|| PathBuf::from("./recordings")) .unwrap_or_else(|| PathBuf::from("./recordings"))
} }
/// Where the daemon writes its log. /// The folder the daemon keeps its daily logs in.
pub fn log_file() -> Option<PathBuf> { pub fn log_dir() -> Option<PathBuf> {
let dir = data_dir()?.join("logs"); let dir = data_dir()?.join("logs");
std::fs::create_dir_all(&dir).ok()?; std::fs::create_dir_all(&dir).ok()?;
Some(dir.join("daemon.log")) Some(dir)
}
/// The `--log-file` the app starts the daemon with.
///
/// The daemon takes the stem of the path and adds the date and the extension (see `init_logging`
/// in `record-daemon/src/main.rs`), so it writes `daemon.YYYY-MM-DD.log` beside this path
/// rather than the path itself.
pub fn log_file() -> Option<PathBuf> {
Some(log_dir()?.join("daemon.log"))
} }
/// Find the record-daemon binary next to the app, in an installed `resources` folder, or in a /// Find the record-daemon binary next to the app, in an installed `resources` folder, or in a
@@ -147,20 +156,68 @@ pub async fn ensure_running() -> Result<(), String> {
} }
} }
/// The last `n` lines of the daemon log. /// The last `n` lines of the log the daemon is writing now.
pub fn read_logs(n: usize) -> Result<String, String> { pub fn read_logs(n: usize) -> Result<String, String> {
let path = log_file().ok_or_else(|| "no data directory for the daemon log".to_string())?; let path = current_log().ok_or_else(|| "the recorder has written no log yet".to_string())?;
let text = std::fs::read_to_string(&path) let text = std::fs::read_to_string(&path)
.map_err(|e| format!("cannot read {}: {e}", path.display()))?; .map_err(|e| format!("cannot read {}: {e}", path.display()))?;
let lines: Vec<&str> = text.lines().rev().take(n).collect(); let lines: Vec<String> = text.lines().rev().take(n).map(strip_ansi).collect();
Ok(lines.into_iter().rev().collect::<Vec<_>>().join("\n")) Ok(lines.into_iter().rev().collect::<Vec<_>>().join("\n"))
} }
/// The log path as text, for the About tab. /// What a log line says without the color codes.
///
/// The daemon used to write ANSI escapes into the file, so lines from before that fix carry
/// them. `ESC [ params final` is the only form tracing emitted.
fn strip_ansi(line: &str) -> String {
if !line.contains('\u{1b}') {
return line.to_string();
}
let mut out = String::with_capacity(line.len());
let mut chars = line.chars();
while let Some(c) = chars.next() {
if c != '\u{1b}' {
out.push(c);
} else if chars.next() == Some('[') {
for c in chars.by_ref() {
if ('@'..='~').contains(&c) {
break;
}
}
}
}
out
}
/// The log file the daemon is appending to now, as text for the Advanced tab.
pub fn log_path() -> String { pub fn log_path() -> String {
log_file() current_log()
.map(|p| p.display().to_string()) .map(|p| p.display().to_string())
.unwrap_or_default() .unwrap_or_else(|| "None yet".to_string())
}
/// The log file the daemon is appending to now.
pub fn current_log() -> Option<PathBuf> {
let dir = data_dir()?.join("logs");
newest_log(&dir)
}
/// The newest daily file in the logs folder.
///
/// The daemon rolls the log over at midnight, so the folder holds one file per day and the
/// newest is the one still being written. The date in the name is in ISO order, so comparing
/// names finds it without reading each file's timestamp.
fn newest_log(dir: &Path) -> Option<PathBuf> {
std::fs::read_dir(dir)
.ok()?
.filter_map(|entry| {
let path = entry.ok()?.path();
let name = path.file_name()?.to_str()?;
let date = name.strip_prefix("daemon.")?.strip_suffix(".log")?;
date.starts_with(|c: char| c.is_ascii_digit())
.then_some(path)
})
.max()
} }
/// Open a folder. /// Open a folder.
@@ -172,3 +229,42 @@ pub fn open_folder(path: &Path) {
#[cfg(not(windows))] #[cfg(not(windows))]
let _ = path; let _ = path;
} }
#[cfg(test)]
mod tests {
use super::*;
fn temp_dir() -> PathBuf {
let dir = std::env::temp_dir().join(format!("leaguerecorder-{}", uuid::Uuid::new_v4()));
std::fs::create_dir_all(&dir).unwrap();
dir
}
#[test]
fn the_newest_day_is_the_log_the_daemon_writes() {
let dir = temp_dir();
std::fs::write(dir.join("daemon.2026-11-21.log"), "yesterday").unwrap();
let today = dir.join("daemon.2026-11-22.log");
std::fs::write(&today, "today").unwrap();
std::fs::write(dir.join("notes.txt"), "not a log").unwrap();
assert_eq!(newest_log(&dir), Some(today));
let _ = std::fs::remove_dir_all(dir);
}
#[test]
fn a_folder_without_a_log_has_no_log_to_read() {
let dir = temp_dir();
assert_eq!(newest_log(&dir), None);
let _ = std::fs::remove_dir_all(dir);
}
#[test]
fn a_log_line_loses_its_color_codes() {
let line =
"\u{1b}[2m2026-11-23T23:06:51Z\u{1b}[0m \u{1b}[32m INFO\u{1b}[0m record_daemon: ready";
assert_eq!(
strip_ansi(line),
"2026-11-23T23:06:51Z INFO record_daemon: ready"
);
}
}
+5 -1
View File
@@ -629,7 +629,11 @@ fn init_logging(level: &str, log_file: Option<&std::path::Path>) {
tracing_subscriber::registry() tracing_subscriber::registry()
.with(filter) .with(filter)
.with(tracing_subscriber::fmt::layer().with_writer(non_blocking)) .with(
tracing_subscriber::fmt::layer()
.with_writer(non_blocking)
.with_ansi(false),
)
.init(); .init();
eprintln!("Logging to file: {}", log_path.display()); eprintln!("Logging to file: {}", log_path.display());