From adbd8a41f9d294c57e415128bcaf35d815bdee88 Mon Sep 17 00:00:00 2001 From: Sola Date: Sat, 22 Nov 2025 17:12:49 +0800 Subject: [PATCH] appender: fix `max_files` integer underflow when set to zero (#3348) ## Motivation When `max_files` set to zero, [rolling.rs:695](https://github.com/tokio-rs/tracing/blob/c01d4fd9def2fb061669a310598095c789ca0a32/tracing-appender/src/rolling.rs#L695) will cause integer underflow and panicking in debug build. In my opinion the API should prevent this from happening as "zero" is a valid `usize` value to pass in. ## Solution Currently, in release builds, if `max_files` is set to zero, it behaves just like `u64::MAX` on `x86_64` platforms. Therefore, I decided to simply make `zero == None`, which should align with the existing behavior but without the panicking. I believe this can be considered as "non-breaking". --- tracing-appender/src/rolling/builder.rs | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/tracing-appender/src/rolling/builder.rs b/tracing-appender/src/rolling/builder.rs index 85d6baac..06455c39 100644 --- a/tracing-appender/src/rolling/builder.rs +++ b/tracing-appender/src/rolling/builder.rs @@ -195,7 +195,7 @@ impl Builder { /// 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. + /// If `0` is supplied, the `RollingAppender` will not remove any files. /// /// Files are considered candidates for deletion based on the following /// criteria: @@ -232,7 +232,8 @@ impl Builder { #[must_use] pub fn max_log_files(self, n: usize) -> Self { Self { - max_files: Some(n), + // Setting `n` to 0 will disable the max files (effectively make it infinite). + max_files: Some(n).filter(|&n| n > 0), ..self } }