当我尝试使用
tracing-appender
时,我注意到控制台中的时间与文件中的时间不匹配。我怎样才能让他们在同一时间?
use std::io;
use std::path::Path;
use tracing::{debug, error, info, trace, warn, Level};
use tracing_appender::non_blocking::WorkerGuard;
use tracing_subscriber::{
fmt::{self, writer::MakeWriterExt},
prelude::*,
};
#[tokio::main]
async fn main() -> Result<(), anyhow::Error> {
let _guard = init_tracing_subscriber(Some("./log"))?;
trace!("Hello, world!");
debug!("Hello, world!");
info!("Hello, world!");
warn!("Hello, world!");
error!("Hello, world!");
Ok(())
}
fn init_tracing_subscriber<P: AsRef<Path>>(
log_dir: Option<P>,
) -> Result<Option<WorkerGuard>, anyhow::Error> {
let mut guard = None;
let file_log = log_dir
.map(|p| tracing_appender::non_blocking(tracing_appender::rolling::daily(p, "server")))
.map(|(none_blocking, g)| {
guard = Some(g);
fmt::Layer::new()
.with_writer(none_blocking.with_max_level(Level::WARN))
.with_ansi(false)
});
let console_log = fmt::Layer::new()
.with_ansi(true)
.with_writer(io::stderr.with_min_level(Level::WARN).or_else(io::stdout));
let subscriber = tracing_subscriber::registry()
.with(file_log)
.with(console_log);
subscriber.try_init()?;
Ok(guard)
}
还有,关于时间格式化的问题,我需要单独格式化时间吗?
2023-04-18T08:42:32.961016Z DEBUG demo: Hello, world!
2023-04-18T08:42:32.961379Z INFO demo: Hello, world!
2023-04-18T08:42:32.961808Z WARN demo: Hello, world!
2023-04-18T08:42:32.962337Z ERROR demo: Hello, world!
2023-04-18T08:42:32.961766Z WARN demo: Hello, world!
2023-04-18T08:42:32.962216Z ERROR demo: Hello, world!
注意到它们不在同一时间让我有点困扰。 网上没查到资料,特来求助