To prevent log files from growing indefinitely, use Logger::rotate. This method requires three parameters:
Criterion: Defines when rotation happens.
Criterion::Age(Age): Rotates based on time (e.g., Age::Day, Age::Hour).Criterion::Size(usize): Rotates when the file exceeds a certain size in bytes.Criterion::AgeOrSize(...): Rotates when either limit is reached.
Naming: Defines how the old file is renamed.
Naming::Timestamps: Renames to include a timestamp (e.g., foo_r2020-11-16_08-56-52.log).Naming::Numbers: Renames using a sequence of numbers (e.g., foo_r00000.log).
Cleanup: Defines how many files to keep.
Cleanup::KeepLogFiles(n): Retains n log files, deleting older ones.Cleanup::KeepCompressedFiles(n): Retains n files and compresses them.Cleanup::KeepLogAndCompressedFiles(n, m): Retains n uncompressed and m compressed files.Cleanup::Never: Keeps all files.
When rotation occurs, the active file is always named with the infix rCURRENT (e.g., foo_rCURRENT.log).
use flexi_logger::{Age, Cleanup, Criterion, FileSpec, Logger, Naming};
use log::{error, warn, info};
fn main() -> Result<(), Box<dyn std::error::Error>> {
Logger::try_with_str("info")?
.log_to_file(
FileSpec::default()
)
.rotate(
Criterion::Age(Age::Day), // create a new file every day
Naming::Timestamps, // use timestamps in rotated filenames
Cleanup::KeepLogFiles(7), // keep at most 7 log files
)
.start()?;
error!("This is an error message");
Ok(())
}