Skip to main content

file_appender/
file_appender.rs

1//! Demonstrates the `FileAppender`: log to the console and to a file at the
2//! same time via `Logger::builder`.
3
4use std::io::Read;
5
6use log4rc::{ConsoleAppender, FileAppender, LogLevel, Logger, SimpleLayout};
7
8fn main() {
9    let log_path = std::env::temp_dir().join("log4rc-file-appender.log");
10
11    Logger::builder(LogLevel::Info)
12        .appender(Box::new(ConsoleAppender::new(Box::new(SimpleLayout))))
13        .appender(Box::new(
14            FileAppender::open(&log_path, Box::new(SimpleLayout))
15                .expect("failed to open log file"),
16        ))
17        .init();
18
19    log4rc::info!("Writing to console and file");
20    log4rc::error!("An error also goes to both");
21    log4rc::debug!("Filtered out at Info level");
22
23    // Read the file back to prove the messages were written to disk.
24    let mut contents = String::new();
25    std::fs::File::open(&log_path)
26        .expect("failed to reopen log file")
27        .read_to_string(&mut contents)
28        .expect("failed to read log file");
29
30    println!("\n--- Contents of {} ---", log_path.display());
31    print!("{contents}");
32    let _ = std::fs::remove_file(&log_path);
33}