TITLE: How to Log to Files with Log Rotation in Rust
Use the rotating_file_appender crate to handle file logging with automatic rotation based on size or time.
- Add the dependency to your
Cargo.toml.
[dependencies]
rotating_file_appender = "2.2"
log = "0.4"
- Initialize the appender in
src/main.rsand configure the logger.
use log::{info, LevelFilter};
use rotating_file_appender::{Builder, ConfigBuilder, rotating_file_appender};
use std::io;
fn main() -> io::Result<()> {
let config = ConfigBuilder::default()
.filename("app.log")
.max_size(100_000_000) // 100MB
.build();
let appender = Builder::default()
.config(config)
.build()?;
let logger = rotating_file_appender::Logger::new(appender);
log::set_boxed_logger(Box::new(logger))
.map(|()| log::set_max_level(LevelFilter::Info))
.unwrap();
info!("Application started");
Ok(())
}
- Run your application to generate logs that rotate automatically.
cargo run