instrumentation
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseInstrument with Logfire
使用Logfire埋点
When to Use This Skill
何时使用本技能
Invoke this skill when:
- User asks to "add logfire", "add observability", "add tracing", or "add monitoring"
- User wants to instrument an app with structured logging or tracing (Python, JS/TS, or Rust)
- User mentions Logfire in any context
- User asks to "add logging" or "see what my app is doing"
- User wants to monitor AI/LLM calls (PydanticAI, OpenAI, Anthropic)
- User asks to add observability to an AI agent or LLM pipeline
当出现以下情况时调用本技能:
- 用户要求「添加logfire」、「添加可观测性」、「添加链路追踪」或「添加监控」
- 用户希望为应用接入结构化日志或链路追踪(支持Python、JS/TS或Rust)
- 用户在任何上下文中提到Logfire
- 用户要求「添加日志」或「查看我的应用在做什么」
- 用户希望监控AI/LLM调用(PydanticAI、OpenAI、Anthropic)
- 用户要求为AI Agent或LLM流水线添加可观测性
How Logfire Works
Logfire的工作原理
Logfire is an observability platform built on OpenTelemetry. It captures traces, logs, and metrics from applications. Logfire has native SDKs for Python, JavaScript/TypeScript, and Rust, plus support for any language via OpenTelemetry.
The reason this skill exists is that Claude tends to get a few things subtly wrong with Logfire - especially the ordering of vs calls, the structured logging syntax, and which extras to install. These matter because a misconfigured setup silently drops traces.
configure()instrument_*()Logfire是基于OpenTelemetry构建的可观测性平台,可捕获应用的链路追踪、日志和指标。Logfire为Python、JavaScript/TypeScript和Rust提供原生SDK,同时支持通过OpenTelemetry接入任意语言。
本技能存在的原因是Claude在Logfire的使用上容易出现几个细微错误——尤其是和调用的顺序、结构化日志的语法,以及需要安装的扩展包。这些问题非常重要,因为配置错误的设置会静默丢失链路追踪数据。
configure()instrument_*()Step 1: Detect Language and Frameworks
步骤1:识别语言和框架
Identify the project language and instrumentable libraries:
- Python: Read or
pyproject.toml. Common instrumentable libraries: FastAPI, httpx, asyncpg, SQLAlchemy, psycopg, Redis, Celery, Django, Flask, requests, PydanticAI.requirements.txt - JavaScript/TypeScript: Read . Common frameworks: Express, Next.js, Fastify. Also check for Cloudflare Workers or Deno.
package.json - Rust: Read .
Cargo.toml
Then follow the language-specific steps below.
先确定项目使用的语言和可埋点的库:
- Python:读取或
pyproject.toml。常见可埋点库:FastAPI、httpx、asyncpg、SQLAlchemy、psycopg、Redis、Celery、Django、Flask、requests、PydanticAI。requirements.txt - JavaScript/TypeScript:读取。常见框架:Express、Next.js、Fastify。同时检查是否使用Cloudflare Workers或Deno。
package.json - Rust:读取。
Cargo.toml
之后按照对应语言的步骤操作。
Python
Python
Install with Extras
安装对应扩展
Install with extras matching the detected frameworks. Each instrumented library needs its corresponding extra - without it, the call will fail at runtime with a missing dependency error.
logfireinstrument_*()bash
uv add 'logfire[fastapi,httpx,asyncpg]'The full list of available extras: , , , , , , , , , , , , , , , , , , , , .
fastapistarlettedjangoflaskhttpxrequestsasyncpgpsycopgpsycopg2sqlalchemyredispymongomysqlsqlite3celeryaiohttpaws-lambdasystem-metricslitellmdspygoogle-genai安装带有检测到的框架对应扩展的。每个被埋点的库都需要对应的扩展包,否则调用会在运行时因缺少依赖报错。
logfireinstrument_*()bash
uv add 'logfire[fastapi,httpx,asyncpg]'可用的完整扩展列表:、、、、、、、、、、、、、、、、、、、、。
fastapistarlettedjangoflaskhttpxrequestsasyncpgpsycopgpsycopg2sqlalchemyredispymongomysqlsqlite3celeryaiohttpaws-lambdasystem-metricslitellmdspygoogle-genaiConfigure and Instrument
配置和埋点
This is where ordering matters. initializes the SDK and must come before everything else. The calls register hooks into each library. If you call before , the hooks register but traces go nowhere.
logfire.configure()instrument_*()instrument_*()configure()python
import logfire这一步的顺序非常重要。会初始化SDK,必须放在所有操作之前。调用会为每个库注册钩子。如果在之前调用,钩子会注册成功但链路数据不会被上报。
logfire.configure()instrument_*()configure()instrument_*()python
import logfire1. Configure first - always
1. 首先配置,始终放在第一步
logfire.configure()
logfire.configure()
2. Instrument libraries - after configure, before app starts
2. 为库埋点 - 配置完成后、应用启动前执行
logfire.instrument_fastapi(app)
logfire.instrument_httpx()
logfire.instrument_asyncpg()
Placement rules:
- `logfire.configure()` goes in the application entry point (`main.py`, or the module that creates the app)
- Call it **once per process** - not inside request handlers, not in library code
- `instrument_*()` calls go right after `configure()`
- Web framework instrumentors (`instrument_fastapi`, `instrument_flask`, `instrument_django`) need the app instance as an argument. HTTP client and database instrumentors (`instrument_httpx`, `instrument_asyncpg`) are global and take no arguments.
- In **Gunicorn** deployments, call `logfire.configure()` inside the `post_fork` hook, not at module level - each worker is a separate processlogfire.instrument_fastapi(app)
logfire.instrument_httpx()
logfire.instrument_asyncpg()
放置规则:
- `logfire.configure()`放在应用入口文件(`main.py`,或创建应用的模块)
- **每个进程仅调用一次** - 不要在请求处理函数内调用,也不要在库代码中调用
- `instrument_*()`调用紧跟在`configure()`之后
- Web框架埋点方法(`instrument_fastapi`、`instrument_flask`、`instrument_django`)需要传入应用实例作为参数。HTTP客户端和数据库埋点方法(`instrument_httpx`、`instrument_asyncpg`)是全局的,不需要参数。
- 在**Gunicorn**部署场景下,在`post_fork`钩子内调用`logfire.configure()`,不要在模块顶层调用——每个工作进程都是独立的进程。Structured Logging
结构化日志
Replace and calls with Logfire's structured logging. The key pattern: use placeholders with keyword arguments, never f-strings.
print()logging.*(){key}python
undefined将和调用替换为Logfire的结构化日志。核心规则:使用带关键字参数的占位符,不要使用f-string。
print()logging.*(){key}python
undefinedCorrect - each {key} becomes a searchable attribute in the Logfire UI
正确 - 每个{key}都会成为Logfire UI中可搜索的属性
logfire.info("Created user {user_id}", user_id=uid)
logfire.error("Payment failed {amount} {currency}", amount=100, currency="USD")
logfire.info("Created user {user_id}", user_id=uid)
logfire.error("Payment failed {amount} {currency}", amount=100, currency="USD")
Wrong - creates a flat string, nothing is searchable
错误 - 只会生成扁平字符串,没有可搜索的属性
logfire.info(f"Created user {uid}")
For grouping related operations and measuring duration, use spans:
```python
with logfire.span("Processing order {order_id}", order_id=order_id):
items = await fetch_items(order_id)
total = calculate_total(items)
logfire.info("Calculated total {total}", total=total)For exceptions, use which automatically captures the traceback:
logfire.exception()python
try:
await process_order(order_id)
except Exception:
logfire.exception("Failed to process order {order_id}", order_id=order_id)
raiselogfire.info(f"Created user {uid}")
如果需要对相关操作分组并统计耗时,可以使用跨度(span):
```python
with logfire.span("Processing order {order_id}", order_id=order_id):
items = await fetch_items(order_id)
total = calculate_total(items)
logfire.info("Calculated total {total}", total=total)处理异常时使用,它会自动捕获回溯信息:
logfire.exception()python
try:
await process_order(order_id)
except Exception:
logfire.exception("Failed to process order {order_id}", order_id=order_id)
raiseAI/LLM Instrumentation (Python)
AI/LLM埋点(Python)
Logfire auto-instruments AI libraries to capture LLM calls, token usage, tool invocations, and agent runs.
bash
uv add 'logfire[pydantic-ai]'Logfire会自动为AI库埋点,捕获LLM调用、Token使用量、工具调用和Agent运行数据。
bash
uv add 'logfire[pydantic-ai]'or: uv add 'logfire[openai]' / uv add 'logfire[anthropic]'
或:uv add 'logfire[openai]' / uv add 'logfire[anthropic]'
Available AI extras: `pydantic-ai`, `openai`, `anthropic`, `litellm`, `dspy`, `google-genai`.
```python
logfire.configure()
logfire.instrument_pydantic_ai() # captures agent runs, tool calls, LLM request/response
可用的AI扩展:`pydantic-ai`、`openai`、`anthropic`、`litellm`、`dspy`、`google-genai`。
```python
logfire.configure()
logfire.instrument_pydantic_ai() # 捕获Agent运行、工具调用、LLM请求/响应or:
或:
logfire.instrument_openai() # captures chat completions, embeddings, token counts
logfire.instrument_anthropic() # captures messages, token usage
For PydanticAI, each agent run becomes a parent span containing child spans for every tool call and LLM request.
---logfire.instrument_openai() # 捕获聊天补全、embedding、Token计数
logfire.instrument_anthropic() # 捕获消息、Token使用量
对于PydanticAI,每个Agent运行都会成为父跨度,包含所有工具调用和LLM请求的子跨度。
---JavaScript / TypeScript
JavaScript / TypeScript
Install
安装
bash
undefinedbash
undefinedNode.js
Node.js
npm install @pydantic/logfire-node
npm install @pydantic/logfire-node
Cloudflare Workers
Cloudflare Workers
npm install @pydantic/logfire-cf-workers logfire
npm install @pydantic/logfire-cf-workers logfire
Next.js / generic
Next.js / 通用场景
npm install logfire
undefinednpm install logfire
undefinedConfigure
配置
Node.js (Express, Fastify, etc.) - create an loaded before your app:
instrumentation.tstypescript
import * as logfire from '@pydantic/logfire-node'
logfire.configure()Launch with:
node --require ./instrumentation.js app.jsThe SDK auto-instruments common libraries when loaded before the app. Set in your environment or pass to .
LOGFIRE_TOKENtokenconfigure()Cloudflare Workers - wrap your handler with :
instrument()typescript
import { instrument } from '@pydantic/logfire-cf-workers'
export default instrument(handler, {
service: { name: 'my-worker', version: '1.0.0' }
})Next.js - set environment variables for OpenTelemetry export:
OTEL_EXPORTER_OTLP_TRACES_ENDPOINT=https://logfire-api.pydantic.dev/v1/traces
OTEL_EXPORTER_OTLP_HEADERS=Authorization=<your-write-token>Node.js(Express、Fastify等) - 创建一个在应用启动前加载的文件:
instrumentation.tstypescript
import * as logfire from '@pydantic/logfire-node'
logfire.configure()启动命令:
node --require ./instrumentation.js app.jsSDK在应用加载前启动时会自动为常见库埋点。在环境变量中设置,或向传入参数。
LOGFIRE_TOKENconfigure()tokenCloudflare Workers - 使用包裹你的处理函数:
instrument()typescript
import { instrument } from '@pydantic/logfire-cf-workers'
export default instrument(handler, {
service: { name: 'my-worker', version: '1.0.0' }
})Next.js - 为OpenTelemetry导出设置环境变量:
OTEL_EXPORTER_OTLP_TRACES_ENDPOINT=https://logfire-api.pydantic.dev/v1/traces
OTEL_EXPORTER_OTLP_HEADERS=Authorization=<your-write-token>Structured Logging (JS/TS)
结构化日志(JS/TS)
typescript
// Structured attributes as second argument
logfire.info('Created user', { user_id: uid })
logfire.error('Payment failed', { amount: 100, currency: 'USD' })
// Spans
logfire.span('Processing order', { order_id }, {}, async () => {
logfire.info('Processing step completed')
})
// Error reporting
logfire.reportError('order processing', error)Log levels: , , , , , , .
tracedebuginfonoticewarnerrorfataltypescript
// 结构化属性作为第二个参数
logfire.info('Created user', { user_id: uid })
logfire.error('Payment failed', { amount: 100, currency: 'USD' })
// 跨度
logfire.span('Processing order', { order_id }, {}, async () => {
logfire.info('Processing step completed')
})
// 错误上报
logfire.reportError('order processing', error)日志级别:、、、、、、。
tracedebuginfonoticewarnerrorfatalRust
Rust
Install
安装
toml
[dependencies]
logfire = "0.6"toml
[dependencies]
logfire = "0.6"Configure
配置
rust
let shutdown_handler = logfire::configure()
.install_panic_handler()
.finish()?;Set in your environment or use the Logfire CLI to select a project.
LOGFIRE_TOKENrust
let shutdown_handler = logfire::configure()
.install_panic_handler()
.finish()?;在环境变量中设置,或使用Logfire CLI选择项目。
LOGFIRE_TOKENStructured Logging (Rust)
结构化日志(Rust)
The Rust SDK is built on and - existing macros work automatically.
tracingopentelemetrytracingrust
// Spans
logfire::span!("processing order", order_id = order_id).in_scope(|| {
// traced code
});
// Events
logfire::info!("Created user {user_id}", user_id = uid);Always call before program exit to flush data.
shutdown_handler.shutdown()Rust SDK基于和构建——现有宏可以自动兼容。
tracingopentelemetrytracingrust
// 跨度
logfire::span!("processing order", order_id = order_id).in_scope(|| {
// 被埋点的代码
});
// 事件
logfire::info!("Created user {user_id}", user_id = uid);务必在程序退出前调用刷新数据。
shutdown_handler.shutdown()Verify
验证
After instrumentation, verify the setup works:
- Run to check authentication (or set
logfire auth)LOGFIRE_TOKEN - Start the app and trigger a request
- Check https://logfire.pydantic.dev/ for traces
If traces aren't appearing: check that is called before (Python), check that is set, and check that the correct packages/extras are installed.
configure()instrument_*()LOGFIRE_TOKEN埋点完成后,验证配置是否生效:
- 运行检查认证状态(或设置
logfire auth)LOGFIRE_TOKEN - 启动应用并触发一次请求
- 访问https://logfire.pydantic.dev/ 查看链路数据
如果没有出现链路数据:检查Python场景下是否在之前调用,检查是否设置,检查是否安装了正确的包/扩展。
configure()instrument_*()LOGFIRE_TOKENReferences
参考资料
Detailed patterns and integration tables, organized by language:
- Python: (log levels, spans, stdlib integration, metrics, capfire testing) and
${CLAUDE_PLUGIN_ROOT}/skills/instrumentation/references/python/logging-patterns.md(full instrumentor table with extras)${CLAUDE_PLUGIN_ROOT}/skills/instrumentation/references/python/integrations.md - JavaScript/TypeScript: (log levels, spans, error handling, config) and
${CLAUDE_PLUGIN_ROOT}/skills/instrumentation/references/javascript/patterns.md(Node.js, Cloudflare Workers, Next.js, Deno setup)${CLAUDE_PLUGIN_ROOT}/skills/instrumentation/references/javascript/frameworks.md - Rust: (macros, spans, tracing/log crate integration, async, shutdown)
${CLAUDE_PLUGIN_ROOT}/skills/instrumentation/references/rust/patterns.md
按语言分类的详细用法和集成表:
- Python:(日志级别、跨度、标准库集成、指标、capfire测试)和
${CLAUDE_PLUGIN_ROOT}/skills/instrumentation/references/python/logging-patterns.md(完整埋点方法和对应扩展表)${CLAUDE_PLUGIN_ROOT}/skills/instrumentation/references/python/integrations.md - JavaScript/TypeScript:(日志级别、跨度、错误处理、配置)和
${CLAUDE_PLUGIN_ROOT}/skills/instrumentation/references/javascript/patterns.md(Node.js、Cloudflare Workers、Next.js、Deno配置)${CLAUDE_PLUGIN_ROOT}/skills/instrumentation/references/javascript/frameworks.md - Rust:(宏、跨度、tracing/log crate集成、异步、关闭流程)
${CLAUDE_PLUGIN_ROOT}/skills/instrumentation/references/rust/patterns.md