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 <nick@hashicorp.com>
This commit is contained in:
Gabriel Goller 2025-08-30 14:48:13 +02:00 committed by GitHub
parent 4c52ca5266
commit c036318aa3
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 11 additions and 2 deletions

View File

@ -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))

View File

@ -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