英文:
Custom trace formatting using tracing-subscriber
问题
我正在尝试使用 tracing-subscriber
crate 进行日志记录。到目前为止,我已经成功使用文件滚动,并将事件记录在文件中。
let appender = tracing_appender::rolling::daily("/logs", "log_test.log");
let (non_blocking_appender, _guard) = tracing_appender::non_blocking(appender);
tracing_subscriber::fmt().with_writer(non_blocking_appender).with_ansi(false).init();
info!("logging info!");
输出:
2023-07-13T09:48:10.321104Z INFO logging: logging info!
我想要自定义消息的格式,像这样:
[年-月-日 时:分:秒] LEVEL: 消息
我尝试过使用 event_format
和 with_timer
,但如果我使用它们,init()
方法将不再可用:
let timer = time::format_description::parse("[year]-[month padding:zero]-[day padding:zero] [hour]:[minute]:[second]").expect("Cataplum");
let timer_format = fmt::format().with_timer(timer);
let subscriber = tracing_subscriber::fmt().with_writer(non_blocking_appender).with_timer(timer_format);
是否有一种简单的方法来格式化这条消息?
英文:
I am trying to use tracing-subscriber
crate for logging purposes. So far, I was able to use the file rolling correctly and log the events in a file.
let appender = tracing_appender::rolling::daily("/logs", "log_test.log");
let (non_blocking_appender, _guard) = tracing_appender::non_blocking(appender);
tracing_subscriber::fmt().with_writer(non_blocking_appender).with_ansi(false).init();
info!("logging info!");
Output:
2023-07-13T09:48:10.321104Z INFO logging: logging info!
I want to customize the message like this:
[year-month-day hour:minute:seconds] LEVEL: message
I've tried both the event_format
and with_timer
, but if I use them, the init()
method is not longer available:
let timer = time::format_description::parse("[year]-[month padding:zero]-[day padding:zero] [hour]:[minute]:[second]").expect("Cataplum");
let timer_format = fmt::format().with_timer(timer);
let subscriber = tracing_subscriber::fmt().with_writer(non_blocking_appender).with_timer(timer_format);
Is there an easy way for format this message?
答案1
得分: 1
你可以这样设置时间格式:
let timer = time::format_description::parse(
"[年]-[月 padding:zero]-[日 padding:zero] [小时]:[分钟]:[秒]"
)
.expect("Cataplum");
let time_offset =
time::UtcOffset::current_local_offset().unwrap_or_else(|_| time::UtcOffset::UTC);
let timer = fmt::time::OffsetTime::new(time_offset, timer);
let subscriber = tracing_subscriber::fmt()
.with_write(non_blocking_appender)
.with_timer(timer)
.init();
注意:我已经去掉了HTML实体编码,以便更清晰地显示代码部分。
英文:
You can set a time format this way:
let timer = time::format_description::parse(
"[year]-[month padding:zero]-[day padding:zero] [hour]:[minute]:[second]",
)
.expect("Cataplum");
let time_offset =
time::UtcOffset::current_local_offset().unwrap_or_else(|_| time::UtcOffset::UTC);
let timer = fmt::time::OffsetTime::new(time_offset, timer);
let subscriber = tracing_subscriber::fmt()
.with_write(non_blocking_appender)
.with_timer(timer)
.init();
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论