tokio-rs / tracing

Application level tracing for Rust.
https://tracing.rs
MIT License
5.19k stars 677 forks source link

Make Layer::with_writer not truncate the file #3028

Closed wiiznokes closed 2 weeks ago

wiiznokes commented 2 weeks ago

Feature Request

Motivation

I might be wrong, but i think tracing automatically truncate the file given to Layer::with_writer

Proposal

I would like to not truncate the file

mladedav commented 2 weeks ago

How are you creating the writer/file? tracing just tries to write to anything you give to it.

wiiznokes commented 2 weeks ago

This is the full function

fn init_logging(cmd: &str) {
    use tracing_subscriber::{fmt, Registry};

    let logdir = match dirs::state_dir() {
        Some(dir) => dir.join("pop-launcher/"),
        None => dirs::home_dir()
            .expect("home directory required")
            .join(".cache/pop-launcher"),
    };

    let _ = std::fs::create_dir_all(&logdir);

    let logfile = std::fs::OpenOptions::new()
        .create(true)
        .truncate(false)
        .write(true)
        .open(logdir.join([cmd, ".log"].concat().as_str()).as_path());

    if let Ok(file) = logfile {

        let filter_layer = EnvFilter::try_from_default_env()
            .or_else(|_| EnvFilter::try_new("debug"))
            .unwrap();

        let fmt_layer = fmt::layer()
            .with_target(false)
            .with_timer(fmt::time::ChronoLocal::new("%T".into()))
            .with_writer(file);

        let subscriber = Registry::default().with(filter_layer).with(fmt_layer);

        tracing::subscriber::set_global_default(subscriber).expect("Failed to set subscriber");
    }
}

each time this function is run, the file get override

mladedav commented 2 weeks ago

You should use append instead of write. Please see the relevant docs but the short story is with this configuration the file is not truncated, but the writing starts at the start of the file and overwrites previous contents.

wiiznokes commented 2 weeks ago

Indeed, thanks