From c036318aa317148aa43d338c820d8d40418c8149 Mon Sep 17 00:00:00 2001 From: Gabriel Goller Date: Sat, 30 Aug 2025 14:48:13 +0200 Subject: [PATCH] appender: Prune old files at startup (#2966) The prune_old_logs function only gets called when we rollover the appender. The problem is that at startup we create an initial log file without rolling over, if e.g., the executable then exits before rolling over for the first time, we never call prune_old_logs. E.g.: If we have a tracing-appender that rolls over every minute and we have a max_files parameter of 2. Running the program (which prints a single log line and exits) every minute, will result in a new log file everytime without deleting the old ones. Fixes: #2937 Co-authored-by: Nick Fagerlund --- tracing-appender/src/rolling.rs | 5 +++++ tracing-appender/src/rolling/builder.rs | 8 ++++++-- 2 files changed, 11 insertions(+), 2 deletions(-) diff --git a/tracing-appender/src/rolling.rs b/tracing-appender/src/rolling.rs index 9673f174..1f02ab47 100644 --- a/tracing-appender/src/rolling.rs +++ b/tracing-appender/src/rolling.rs @@ -605,6 +605,11 @@ impl Inner { rotation, max_files, }; + + if let Some(max_files) = max_files { + inner.prune_old_logs(max_files); + } + let filename = inner.join_date(&now); let writer = RwLock::new(create_writer(inner.log_directory.as_ref(), &filename)?); Ok((inner, writer)) diff --git a/tracing-appender/src/rolling/builder.rs b/tracing-appender/src/rolling/builder.rs index 8c92ca12..85d6baac 100644 --- a/tracing-appender/src/rolling/builder.rs +++ b/tracing-appender/src/rolling/builder.rs @@ -189,8 +189,12 @@ impl Builder { /// Keeps the last `n` log files on disk. /// - /// When a new log file is created, if there are `n` or more - /// existing log files in the directory, the oldest will be deleted. + /// When constructing a `RollingFileAppender` or starting a new log file, + /// the appender will delete the oldest matching log files until at most `n` + /// files remain. The exact number of retained files can sometimes dip below + /// the maximum, so if you need to retain `m` log files, specify a max of + /// `m + 1`. + /// /// If no value is supplied, the `RollingAppender` will not remove any files. /// /// Files are considered candidates for deletion based on the following