← 中文资源

简体中文版本

tracing-subscriber

用于组合 Rust tracing 订阅者的工具,包含过滤与格式化层。

阅读英文原文

概述

用于组合 Rust tracing 订阅者的工具,包含过滤与格式化层。

核心 API

  • tracing_subscriber::fmt:安装带默认设置的格式化订阅者。
  • EnvFilter::from_default_env:从 RUST_LOG 环境变量构建过滤器。
  • fmt().json():将事件格式化为 JSON,便于结构化日志管道。

使用注意

过滤器与环境变量结合可灵活控制级别。结构化输出用 json 便于采集系统解析。多个 layer 可组合,分别负责格式化与过滤。订阅者只能安装一次,测试需用 try_init 并处理重复安装错误。

验证方式

以不同过滤指令运行并断言输出范围,切换 json 格式化后验证输出可被 JSON 解析器读取。

版本提示

以上签名与用法以 v0.3 为基准,升级大版本前请对照官方迁移说明确认 API 是否变更。

代码示例

tracing_subscriber::fmt().init();
use tracing_subscriber::EnvFilter;
tracing_subscriber::fmt()
    .with_env_filter(EnvFilter::from_default_env())
    .init();
tracing_subscriber::fmt().json().init();
cargo add tracing-subscriber