SuperAPI AI 工具集

tracing

编程与开发

查看项目

更新于 10-15 20:32

技能介绍

用途:为 Rust 项目引入 tracing 日志体系,把日志视为 span 加字段,而不是 println!。适用于 Axum API、Tokio worker、异步调试,以及通过 RUST_LOG 控制输出。

主要能力与规则:使用 info!、warn!、error!、debug! 并携带结构化字段(如 user_id = %id),不要用 format! 拼成单条消息;在请求、任务、查询等边界建立 span,异步服务用 #[instrument];用 RUST_LOG 或 EnvFilter 过滤,生产环境避免嘈杂 crate 的 trace(如 hyper=info);禁止记录 PII 与密钥(authorization、登录 body、CPF);main 中只初始化一个 subscriber,不要在 handler 里重复 fmt::init。

Subscriber 示例:tracing_subscriber::fmt().with_env_filter(EnvFilter::from_default_env()).json().init(); 开发用 compact/pretty,生产用 JSON。tracing-subscriber 与 tracing 版本需对齐;若已有 OTEL layer 则复用,不要另建并行栈。

Span 用法:#[instrument(skip(db), fields(order_id = %id))] async fn load_order(db: &Db, id: Uuid) {},对连接池等大对象用 skip,err/ret 仅在类型可安全记录时使用。Axum 用 TraceLayer::new_for_http() 并带 http.method、uri、status;请求 id 取 x-request-id 头或在中间件生成。Tokio 中若任务脱离请求,用 Instrument::instrument 包裹。

级别建议:error 为需处理且带 err 的失败;warn 为降级或重试耗尽;info 为业务事件(如订单创建)且克制;debug 为内部流程;trace 为协议级,生产关闭。不要为每条 SQL 打 info,必要时在仓储层用 debug。

反模式:API 中残留 dbg!/println!;记录整个 Json<T> 输入;在热循环每次迭代建 span;在库中 unwrap subscriber 初始化;未用 Layer 组合就同时启用 fmt 与 json 两种格式。

与其他技能集成:Axum 进程见 rust-axum-production,运行时 tokio,HTTP axum,客户端 reqwest(出站 span),测试见 rust-unit-testing(除非 crate 本身测试日志,否则不要断言日志)。完成标准:单一 subscriber、按环境过滤、结构化字段且无密钥、有请求 span(TraceLayer 或等价物)、被触及的服务加 instrument、服务若已用 JSON 日志则生产输出 JSON。