How can append data in WriteLogger if file exist?
synelokk opened this issue · 2 comments
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..
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();
}Oh ok thanks, i will explore more about https://doc.rust-lang.org/std/fs/struct.File.html#method.create