Rust 的一个方便的 tracing 日志初始化库

1,142 阅读1分钟

Rust 中的 tracing 框架,以其功能强大、可扩展性好而著称。这就带来了一个问题,就是使用时对它进行配置和初始化比较麻烦,要写一堆代码。

有一个 crateclia-tracing-config: crates.io/crates/clia… 可以帮助解决这种烦恼。

它还提供了两个额外的功能:

  1. 自动为最新的日志文件添加软链接,这样你就可以使用 tail -F 持续监控日志输出了。
  2. 日志文件名称中的时间、日志内容中的时间,都是采用的本地时间格式。

运行起来的效果如下图所示:

image.png

使用以下一些日志格式设置(后续考虑改为可配置):

  • pretty()
  • with_level(true)
  • with_target(true)
  • with_thread_ids(true)
  • with_thread_names(true)
  • with_source_location(true)

示例

代码初始化示例如下(同时也是默认值):

let _guard = clia_tracing_config::build()
    .filter_level("info")
    .with_ansi(true)
    .to_stdout(false)
    .directory("./logs")
    .file_name("my-service.log")
    .rolling("daily")
    .init();

tracing::info!("logged by tracing");
log::info!("logged by tracing");

只需要一句话,就可以初始化好了。

初始化好后,既可以用 tracing 记日志,也可以用 log 库记日志。

rolling 支持以下一些值:

  • minutely
  • hourly
  • daily
  • never