How to refresh logging file with log4rs crate?

Hi everyone,
I am using log4rs crate for logging my application. I initialize logger and use it as follows

use log::{debug, error, info, trace, warn, LevelFilter, SetLoggerError};
use log4rs::{
    append::{
        console::{ConsoleAppender, Target},
        file::FileAppender,
    },
    config::{Appender, Config, Root},
    encode::pattern::PatternEncoder,
    filter::threshold::ThresholdFilter,
};

fn init_logger(){
    let level = log::LevelFilter::Off;
    let file_path = "tmp/foo.log";

    let stderr = ConsoleAppender::builder().target(Target::Stderr).build();

    let logfile = FileAppender::builder()
        // Pattern: https://docs.rs/log4rs/*/log4rs/encode/pattern/index.html
        .encoder(Box::new(PatternEncoder::new("{d} - {l} - {m}\n")))
        .build(file_path)
        .unwrap();

    let config = Config::builder()
        .appender(Appender::builder().build("logfile", Box::new(logfile)))
        .appender(
            Appender::builder()
                .filter(Box::new(ThresholdFilter::new(level)))
                .build("stderr", Box::new(stderr)),
        )
        .build(
            Root::builder()
                .appender("logfile")
                .appender("stderr")
                .build(LevelFilter::Trace),
        )
        .unwrap();

    let _handle = log4rs::init_config(config);

}

fn main() {
    init_logger();

    error!("Error");
    warn!("Warn");
    info!("Info");
    debug!("Debug");
    trace!("Trace");

}

This code is working. However, when I rerun the code the new logs are appended to foo.log file. Is there anyway to clean this file before logging in it? By te way, I am aware that I can make a build script which first remove it with rm command, then create file again with touch command but I am asking is there anyway to do it with this crates functions.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.