In Rust I use tracing wirte log to file.While the app sleep, log file be created.the app finish ,the log file is empty.
Code:
pub fn tracing_init() {
let env_filter = EnvFilter::try_from_default_env().unwrap_or_else(|_| EnvFilter::new("info"));
// 输出到控制台中
let formatting_layer = fmt::layer().pretty().with_writer(std::io::stderr);
let log_file_name = Local::now().format("%Y-%m-%d").to_string() + ".log";
// 输出到文件中
let file_appender = rolling::daily("logs", log_file_name);
let (non_blocking_appender, _guard) = non_blocking(file_appender);
let file_layer = fmt::layer()
.with_ansi(false)
.with_writer(non_blocking_appender);
// 注册
Registry::default()
.with(env_filter)
// ErrorLayer 可以让 color-eyre 获取到 span 的信息
.with(ErrorLayer::default())
.with(formatting_layer)
.with(file_layer)
.init();
// 安裝 color-eyre 的 panic 处理句柄
color_eyre::install().expect("color_eyre install fail");
}
in main function:
fn main() {
tracing_init();
event!(Level::DEBUG, "aaa:{}", "myu");
info!("info");
debug!("debug");
error!("error");
warn!("warn");
tracing::info!("this is tracing info");
thread::sleep(time::Duration::from_secs(10));
event!(Level::INFO, "aaa:{}", "myu1");
info!("info1");
debug!("debug1");
error!("error1");
warn!("warn1");
tracing::info!("this is tracing info1");
}
the file is created,bug it is empty.
Cargo.toml file is here:
[dependencies]
tracing = "0.1.37"
tracing-subscriber = { version = "0.3.16", features = ["env-filter", "std"] }
tracing-appender="0.2.2"
tracing-error="0.2.0"
color-eyre="0.6.2"
chrono = "0.4"