如何使用tracing-subscriber自定义日志时间戳格式?
如何在tracing-subscriber中自定义日志时间戳格式?
你遇到的问题是因为with_timer方法的参数类型使用错误,直接传递解析后的时间格式对象即可,不需要用fmt::format().with_timer()包装。以下是正确的实现方式:
完整代码示例
use tracing::{info}; use tracing_subscriber::fmt; use tracing_appender; use time::format_description::parse; fn main() { // 配置每日滚动日志文件 let appender = tracing_appender::rolling::daily("/logs", "log_test.log"); let (non_blocking_appender, _guard) = tracing_appender::non_blocking(appender); // 解析自定义时间格式:年-月-日 时:分:秒 let time_format = parse("[year]-[month padding:zero]-[day padding:zero] [hour]:[minute]:[second]") .expect("解析时间格式失败"); // 配置subscriber并初始化 tracing_subscriber::fmt() .with_writer(non_blocking_appender) .with_ansi(false) .with_timer(time_format) // 直接传递解析后的时间格式实例 .init(); info!("logging info!"); }
关键说明
with_timer方法接受的是实现time::format_description::Formattrait的对象,也就是parse函数返回的Format实例,无需额外用fmt::format()包裹。- 运行后日志输出格式会变为:
2023-07-13 09:48:10 INFO logging: logging info!
内容的提问来源于stack exchange,提问作者JuanN
相关产品推荐
相关产品推荐

