Write A Log File With The tracing Rust Crate
rust
```cargo
[dependencies]
tracing = "0.1"
tracing-appender = "0.2"
tracing-subscriber = "0.3"
```
use tracing::{Level, event, instrument};
use std::path::PathBuf;
use std::fs;
#[instrument]
fn main() {
let log_file = PathBuf::from("./example3.log");
let _ = fs::remove_file(&log_file);
let file_appender = tracing_appender::rolling::never(
log_file.parent().unwrap(),
log_file.file_name().unwrap()
);
let (non_blocking, _guard) = tracing_appender::non_blocking(file_appender);
tracing_subscriber::fmt()
.with_ansi(false)
.with_writer(non_blocking)
.init();
event!(Level::INFO, r#"This is the log message"#);
}
This is how I'm writing out a log file in
Rust. It removes the file each time at the
start of the process. Not always what I want,
but super helpful in lots of cases. If I want
to keep the logs going over time, I use
rust
tracing_appender::rolling::hourly()
rust
tracing_appender::rolling::never()