Skip to content

Commit c036318

Browse files
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 <[email protected]>
1 parent 4c52ca5 commit c036318

File tree

2 files changed

+11
-2
lines changed

2 files changed

+11
-2
lines changed

tracing-appender/src/rolling.rs

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -605,6 +605,11 @@ impl Inner {
605605
rotation,
606606
max_files,
607607
};
608+
609+
if let Some(max_files) = max_files {
610+
inner.prune_old_logs(max_files);
611+
}
612+
608613
let filename = inner.join_date(&now);
609614
let writer = RwLock::new(create_writer(inner.log_directory.as_ref(), &filename)?);
610615
Ok((inner, writer))

tracing-appender/src/rolling/builder.rs

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -189,8 +189,12 @@ impl Builder {
189189

190190
/// Keeps the last `n` log files on disk.
191191
///
192-
/// When a new log file is created, if there are `n` or more
193-
/// existing log files in the directory, the oldest will be deleted.
192+
/// When constructing a `RollingFileAppender` or starting a new log file,
193+
/// the appender will delete the oldest matching log files until at most `n`
194+
/// files remain. The exact number of retained files can sometimes dip below
195+
/// the maximum, so if you need to retain `m` log files, specify a max of
196+
/// `m + 1`.
197+
///
194198
/// If no value is supplied, the `RollingAppender` will not remove any files.
195199
///
196200
/// Files are considered candidates for deletion based on the following

0 commit comments

Comments
 (0)