Drakulix / simplelog.rs

Simple Logging Facility for Rust
https://docs.rs/simplelog/
Apache License 2.0
414 stars 71 forks source link

How can append data in WriteLogger if file exist? #117

Closed dhianica closed 1 year ago

dhianica commented 1 year ago

Hi, thanks for create this project. i have a questions,

i have fn like this..

use log::{LevelFilter};
extern crate log;
extern crate simplelog;

use simplelog::*;
use std::fs::File;

pub fn log() {
    CombinedLogger::init(vec![
        TermLogger::new(
            LevelFilter::Info,
            Config::default(),
            TerminalMode::Mixed,
            ColorChoice::Auto,
        ),
        WriteLogger::new(
            LevelFilter::Info,
            Config::default(),
            File::create("logs/info.log").unwrap(),
        ),
    ])
    .unwrap();
}

how can i append data in logs/info.log if file exist? for now i tested run command cargo run again my file always clear..

thanks all..

Drakulix commented 1 year ago

This is not really an issue of simplelog, but rather a symptom of how you open the file.

File::create will always truncate an existing file, as written in it's documentation: https://doc.rust-lang.org/std/fs/struct.File.html#method.create . Those docs also outline a solution, which is to use the OpenOptions-builder instead, which has an explicit append option: https://doc.rust-lang.org/std/fs/struct.OpenOptions.html#method.append .

So your code should look something like this:

extern crate log;
extern crate simplelog;

use simplelog::*;
use log::LevelFilter;
use std::fs::OpenOptions;

pub fn log() {
    CombinedLogger::init(vec![
        TermLogger::new(
            LevelFilter::Info,
            Config::default(),
            TerminalMode::Mixed,
            ColorChoice::Auto,
        ),
        WriteLogger::new(
            LevelFilter::Info,
            Config::default(),
            OpenOptions::new()
                .create(true) // to allow creating the file, if it doesn't exist
                .append(true) // to not truncate the file, but instead add to it
                .open("logs/info.log")
                .unwrap(),
        ),
    ])
    .unwrap();
}
dhianica commented 1 year ago

Oh ok thanks, i will explore more about https://doc.rust-lang.org/std/fs/struct.File.html#method.create