I tried to find an easy way to transfer logs from the console to a file. I can't find a suitable option for me on the Internet. I run 2 threads at once, one of which should receive output from the user, but at the same time, the logs from Raketa interfere with convenient use. After all, when someone interacts with the Web server, the input gets lost. Tell me how I could transfer them to a file?
Code example:
#[rocket::main]
async fn main() {
// Creating thread
thread::spawn(|| {
let rt = Runtime::new().unwrap();
// launching rocket
rt.block_on(async {
// Rocket start
let _start = web_page::rocket().launch().await;
});
});
// Another code
start()
}
Since Rocket's log output is based on the log crate and defaults to using env_logger, you can initialize the logging before starting Rocket to customize the log output.
For example, using fern as the implementation:
cargo.toml
chrono = "0.4.38"
log = "0.4"
fern = "0.7.0"
main.rs
use std::fs::OpenOptions;
use chrono::Local;
use fern::Dispatch;
// init log
fn setup_logging() -> Result<(), fern::InitError> {
let log_file = OpenOptions::new()
.create(true)
.write(true)
.append(true)
.open("output.log")?;
Dispatch::new()
.format(|out, message, record| {
out.finish(format_args!(
"[{}][{}][{}] {}",
Local::now().format("%Y-%m-%d %H:%M:%S"),
record.level(),
record.target(),
message
))
})
.level(log::LevelFilter::Info)
// Do not send to standard output.
// .chain(std::io::stdout())
.chain(log_file)
.apply()?; // Apply the logging configuration
Ok(())
}
#[rocket::main]
async fn main() {
setup_logging().expect("Failed to initialize logging");
// Creating thread
thread::spawn(|| {
let rt = Runtime::new().unwrap();
// launching rocket
rt.block_on(async {
// Rocket start
let _start = web_page::rocket().launch().await;
});
});
// Another code
start()
}