22.1 自动的还��够
§07 讲过 Metrics 和 Traces 面板。但有些事自动采集不到:你自写的业务逻辑、内部服务调用、没被支持的框架。这时得自己插桩。
上个月我一个 Agent 偶发卡顿,自动 trace 只看到"慢",看不到慢在哪。我手动插了一段 span,十秒定位是摘要函数拖了后腿。
22.2 用 context.tracer 手动补
平台基于 OpenInference,在你代码加载前就注入了。自动 span 和手动 span 共享同一个 traceId,自然嵌套。
最常用的 span():
const intent = await context.tracer.span(
"classify_intent", // span 名,别用动态值
async (span) => {
const res = await openai.chat.completions.create({ /* ... */ });
span.setAttributes({ "intent.label": res.choices[0].message.content });
return res;
},
{ "agent.step": "intent" }
);
预期结果:这段逻辑在 Traces 面板里变成一颗可展开的树,耗时、入参、返回值一目了然。
| API | 用途 | 标叔的结论 |
|---|---|---|
span(name, fn, attrs?) |
包一段逻辑,自动管生命周期 | 首选 |
startSpan(name, attrs?) |
手动开,须配对 end() |
跨异步边界 |
setAttributes(attrs) |
给当前 span 打标签 | 过滤维度 |
注意
span 名别用 userId、订单号这类高基数动态值。把它们放
attributes里。否则面板聚合会炸。
22.3 把业务标签打上去
给 span 打业务维度,后面在面板按维度过滤:
context.tracer.setAttributes({
"user.tier": "premium",
"agent.scenario": "customer_service",
});
预期结果:你能在 Traces 里按"付费用户""客服场景"筛出问题链路。
自动能看全貌,手动能看细节。两者配合,Agent 再也没法"暗箱操作"。下一章,我们用 Skills 把上面这些能力快速拼起来。