rust logger non-block
cargo add tracing_appender tracing_error tracing
cargo add tracing-subscriber -F env-filter
add to main function
#![allow(unused)] fn main() { use tracing::{debug, info, warn}; use tracing_appender::{non_blocking, rolling}; use tracing_error::ErrorLayer; use tracing_subscriber::fmt::writer::MakeWriterExt; use tracing_subscriber::{ filter::EnvFilter, fmt, layer::SubscriberExt, util::SubscriberInitExt, Registry, }; let file_appender = rolling::never("logs", "app.log"); let env_filter = EnvFilter::try_from_default_env().unwrap_or_else(|_| EnvFilter::new("info")); // Create a formatting layer for stderr let formatting_layer = fmt::layer() .with_timer(tracing_subscriber::fmt::time::time()) .with_level(true) .pretty() .with_file(true) .with_writer(std::io::stdout); // Create a non-blocking appender let (non_blocking_appender, guard) = non_blocking(file_appender); // Create a file layer with the non-blocking appender let file_layer = fmt::layer() .with_ansi(false) .with_writer(non_blocking_appender); let subscriber = Registry::default() .with(env_filter) .with(ErrorLayer::default()) .with(formatting_layer) .with(file_layer); // Initialize the subscriber tracing::subscriber::set_global_default(subscriber).expect("Failed to set global subscriber"); }