logs: write a log file per run, keep the previous four

voelin-platform::logs writes <state>/voelin/logs/voelin.log (the previous
runs as voelin.1.log ... voelin.4.log; a run past 20 MiB starts a fresh
file). The desktop app logs our crates' information there (VOELIN_LOG
overrides the filter) and warnings to the terminal as before; release
builds on Windows have no terminal. Settings -> Advanced names the file
and opens its folder; crash reports keep their own Open button.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VZBWxxMsxUzp4PSTKVzbZN
This commit is contained in:
Claude committed 2026-10-04 22:12:07 +00:00
1 parent 7433b5a568
commit a88d267937
5 files changed
+235 -9

No files matched your search

+2
View File
@@ -7,11 +7,13 @@
//! - [`notify`]: desktop notifications
//! - [`paths`]: data, config, cache and state directories
//! - [`crash`]: opt-in local crash reports (panic hook)
//! - [`logs`]: the log file, with the previous runs' kept
//! - [`notices`]: third-party notices for the About page
pub mod crash;
pub mod files;
pub mod hotkey;
pub mod logs;
pub mod notices;
pub mod notify;
pub mod paths;
+159
View File
@@ -0,0 +1,159 @@
//! The app's log file: `<state>/logs/voelin.log` for this run, the previous
//! runs' as `voelin.1.log` (the last one) to `voelin.4.log`. A run that writes
//! more than [`MAX_BYTES`] starts a fresh file (the full one moves to
//! `voelin.1.log`), so the logs never fill the disk.
//!
//! ```no_run
//! let log = voelin_platform::logs::LogFile::open(voelin_platform::logs::default_dir())?;
//! // tracing_subscriber::fmt::layer().with_ansi(false).with_writer(move || log.clone())
//! # Ok::<(), std::io::Error>(())
//! ```
use std::fs::{File, OpenOptions};
use std::io::{self, Write};
use std::path::{Path, PathBuf};
use std::sync::{Arc, Mutex, OnceLock, PoisonError};
use crate::paths;
/// The log directory's name under the state directory.
pub const DIR_NAME: &str = "logs";
/// Files kept: this run's and the previous runs'.
pub const KEEP: usize = 5;
/// One file's limit.
pub const MAX_BYTES: u64 = 20 << 20;
const NAME: &str = "voelin";
/// The file this process writes, once [`LogFile::open`] succeeded.
static CURRENT: OnceLock<PathBuf> = OnceLock::new();
/// `<state>/logs`.
pub fn default_dir() -> PathBuf {
paths::state_dir().join(DIR_NAME)
}
/// The log file of this run, if there is one.
pub fn current() -> Option<&'static Path> {
CURRENT.get().map(PathBuf::as_path)
}
/// A log file to write to from any thread; clones write to the same file.
#[derive(Clone)]
pub struct LogFile(Arc<Mutex<Inner>>);
struct Inner {
dir: PathBuf,
file: File,
written: u64,
keep: usize,
max: u64,
}
impl LogFile {
/// Start this run's file in `dir`, moving the previous runs' along.
pub fn open(dir: impl Into<PathBuf>) -> io::Result<Self> {
Self::open_with(dir.into(), KEEP, MAX_BYTES)
}
fn open_with(dir: PathBuf, keep: usize, max: u64) -> io::Result<Self> {
std::fs::create_dir_all(&dir)?;
let file = start(&dir, keep)?;
let _ = CURRENT.set(dir.join(file_name(0)));
Ok(Self(Arc::new(Mutex::new(Inner { dir, file, written: 0, keep, max }))))
}
/// The file being written.
pub fn path(&self) -> PathBuf {
self.lock().dir.join(file_name(0))
}
fn lock(&self) -> std::sync::MutexGuard<'_, Inner> {
self.0.lock().unwrap_or_else(PoisonError::into_inner)
}
}
impl Write for LogFile {
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
let mut inner = self.lock();
if inner.written > 0 && inner.written + buf.len() as u64 > inner.max {
inner.file = start(&inner.dir, inner.keep)?;
inner.written = 0;
}
let n = inner.file.write(buf)?;
inner.written += n as u64;
Ok(n)
}
fn flush(&mut self) -> io::Result<()> {
self.lock().file.flush()
}
}
/// `voelin.log`, `voelin.1.log`, …
fn file_name(n: usize) -> String {
if n == 0 { format!("{NAME}.log") } else { format!("{NAME}.{n}.log") }
}
/// Move the files one along (the oldest goes) and open a new current one.
fn start(dir: &Path, keep: usize) -> io::Result<File> {
let keep = keep.max(1);
let _ = std::fs::remove_file(dir.join(file_name(keep - 1)));
for n in (0..keep - 1).rev() {
let from = dir.join(file_name(n));
if from.exists() {
let _ = std::fs::rename(&from, dir.join(file_name(n + 1)));
}
}
OpenOptions::new().create(true).write(true).truncate(true).open(dir.join(file_name(0)))
}
#[cfg(test)]
mod tests {
use super::*;
fn temp_dir(name: &str) -> PathBuf {
let dir = std::env::temp_dir().join(format!(
"voelin-logs-{name}-{}-{:?}",
std::process::id(),
std::thread::current().id()
));
let _ = std::fs::remove_dir_all(&dir);
dir
}
fn read(dir: &Path, n: usize) -> Option<String> {
std::fs::read_to_string(dir.join(file_name(n))).ok()
}
#[test]
fn each_run_gets_a_file_and_the_oldest_go() {
let dir = temp_dir("runs");
for run in 0..4 {
let mut log = LogFile::open_with(dir.clone(), 3, MAX_BYTES).unwrap();
writeln!(log, "run {run}").unwrap();
}
assert_eq!(read(&dir, 0).as_deref(), Some("run 3\n"));
assert_eq!(read(&dir, 1).as_deref(), Some("run 2\n"));
assert_eq!(read(&dir, 2).as_deref(), Some("run 1\n"));
assert_eq!(read(&dir, 3), None, "only three files are kept");
std::fs::remove_dir_all(&dir).unwrap();
}
#[test]
fn a_full_file_starts_over() {
let dir = temp_dir("full");
let log = LogFile::open_with(dir.clone(), 3, 10).unwrap();
let mut writer = log.clone();
writer.write_all(b"12345678\n").unwrap();
// Clones share the file and its size.
log.clone().write_all(b"abcdef\n").unwrap();
assert_eq!(read(&dir, 0).as_deref(), Some("abcdef\n"));
assert_eq!(read(&dir, 1).as_deref(), Some("12345678\n"));
assert_eq!(log.path(), dir.join("voelin.log"));
// A line longer than the limit still goes out whole.
writer.write_all(b"a line longer than ten bytes\n").unwrap();
assert_eq!(read(&dir, 0).as_deref(), Some("a line longer than ten bytes\n"));
std::fs::remove_dir_all(&dir).unwrap();
}
}
+30 -5
View File
@@ -5,14 +5,39 @@
#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]
use anyhow::Result;
use tracing_subscriber::EnvFilter;
use tracing_subscriber::{EnvFilter, Layer, fmt, prelude::*};
use voelin_platform::logs;
/// What the log file gets without `VOELIN_LOG`: our crates' information,
/// everyone's warnings.
const FILE_FILTER: &str = "warn,voelin=info,voelin_ui=info,voelin_core=info,voelin_media=info,\
voelin_stream=info,voelin_audio=info,voelin_store=info,voelin_myts=info,voelin_observer=info,\
voelin_query=info,voelin_gateway_proto=info,voelin_platform=info,tsclientlib=info";
fn main() -> Result<()> {
tracing_subscriber::fmt()
.with_env_filter(
EnvFilter::try_from_default_env().unwrap_or_else(|_| EnvFilter::new("warn")),
// The terminal (RUST_LOG, warnings by default) and the log file in the
// state directory (VOELIN_LOG, `FILE_FILTER` by default): release builds
// on Windows have no terminal.
let file = logs::LogFile::open(logs::default_dir());
let console = fmt::layer()
.with_writer(std::io::stderr)
.with_filter(EnvFilter::try_from_default_env().unwrap_or_else(|_| EnvFilter::new("warn")));
let to_file = file.as_ref().ok().map(|log| {
let log = log.clone();
fmt::layer().with_ansi(false).with_writer(move || log.clone()).with_filter(
EnvFilter::try_from_env("VOELIN_LOG").unwrap_or_else(|_| EnvFilter::new(FILE_FILTER)),
)
.init();
});
tracing_subscriber::registry().with(console).with(to_file).init();
match &file {
Ok(log) => tracing::info!(
version = env!("CARGO_PKG_VERSION"),
os = std::env::consts::OS,
log = %log.path().display(),
"Voelin starting"
),
Err(error) => tracing::warn!(%error, "no log file this time"),
}
let options = voelin_ui::RunOptions {
setting_overrides: setting_overrides(std::env::args().skip(1)),
..Default::default()
+26 -3
View File
@@ -333,8 +333,11 @@ impl App {
fetch_images: p.get(&CACHE_FETCH_IMAGES),
progress_ms: p.get(&FILES_PROGRESS_MS).to_string().into(),
preview_kb: p.get(&UI_IMAGE_PREVIEW_KB).to_string().into(),
logs: "Logs go to the terminal the app was started from (standard error); RUST_LOG=voelin_core=debug,voelin_ui=debug shows more.".into(),
crash_dir: voelin_platform::crash::dir().map(|d| d.display().to_string()).unwrap_or_default().into(),
logs: log_text().into(),
crash_dir: voelin_platform::crash::dir()
.map(|d| d.display().to_string())
.unwrap_or_default()
.into(),
});
self.refresh_account();
}
@@ -722,8 +725,14 @@ impl App {
self.refresh_pages();
}
/// The folder with the log files.
pub(crate) fn open_logs(&mut self) {
self.open_crash_folder();
let dir = voelin_platform::logs::current().and_then(std::path::Path::parent);
let result = dir.ok_or_else(|| "no log file".to_owned());
if let Err(e) = result.and_then(|dir| crate::app::open_path(dir).map_err(|e| e.to_string()))
{
self.set_status(format!("Cannot open the log folder: {e}"));
}
}
// Integrations.
@@ -1419,3 +1428,17 @@ mod tests {
assert_eq!(rule_text(&PermRule::default()), "nobody");
}
}
/// Where the logs go, for the Advanced page.
fn log_text() -> String {
match voelin_platform::logs::current() {
Some(path) => format!(
"This run logs to {} (the previous runs' next to it, the last as voelin.1.log). \
VOELIN_LOG=voelin_core=debug,voelin_ui=debug logs more; warnings also go to the terminal.",
path.display()
),
None => "Logs go to the terminal the app was started from (standard error); \
RUST_LOG=voelin_core=debug,voelin_ui=debug shows more."
.into(),
}
}
@@ -1262,6 +1262,23 @@ export component AdvancedSection inherits VerticalLayout {
Hint {
text: Bridge.advanced.logs;
}
HorizontalLayout {
spacing: Theme.space-3;
Text {
text: @tr("Log files");
color: Theme.text-secondary;
font-size: Theme.font-sm;
vertical-alignment: center;
horizontal-stretch: 1;
overflow: elide;
}
Button {
small: true;
icon: Icons.folder-open;
text: @tr("Open");
clicked => { Bridge.open-logs(); }
}
}
HorizontalLayout {
spacing: Theme.space-3;
Text {
@@ -1277,7 +1294,7 @@ export component AdvancedSection inherits VerticalLayout {
icon: Icons.folder-open;
text: @tr("Open");
enabled: Bridge.advanced.crash-dir != "";
clicked => { Bridge.open-logs(); }
clicked => { Bridge.open-crash-folder(); }
}
}
}