logfire-query

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Query Logfire Data

查询Logfire数据

When to Use This Skill

何时使用此技能

Invoke this skill when:
  • User wants to query traces, logs, spans, or metrics from Logfire
  • User wants to search for specific events, errors, or patterns in telemetry data
  • User wants to analyze OpenTelemetry data stored in Logfire
  • User wants to add programmatic query capabilities to their code
  • User asks to "query logfire", "search traces", "find logs", "get metrics"
  • User wants to build reports or dashboards from Logfire data
在以下场景调用此技能:
  • 用户想要从Logfire查询traces、logs、spans或metrics
  • 用户想要在遥测数据中搜索特定事件、错误或模式
  • 用户想要分析存储在Logfire中的OpenTelemetry数据
  • 用户想要为其代码添加程序化查询功能
  • 用户要求“查询logfire”、“搜索traces”、“查找logs”、“获取metrics”
  • 用户想要基于Logfire数据构建报表或仪表板

Two Approaches

两种查询方式

AspectMCP
query_run
REST API
/v1/query
Best forInteractive exploration in ClaudeAdding query code to a project
AuthOAuth via MCP sessionBearer read token
SetupAlready configured via pluginNeed a read token
FormatsJSON rowsJSON, CSV, Apache Arrow
Default windowLast 30 minLast 24 hours
Max range14 days14 days
Row limitMust be in SQLDefault 500, max 10,000
维度MCP
query_run
REST API
/v1/query
最佳适用场景在Claude中进行交互式探索为项目添加查询代码
认证方式通过MCP会话进行OAuth认证Bearer只读令牌
设置要求已通过插件配置完成需要只读令牌
输出格式JSON行JSON、CSV、Apache Arrow
默认时间窗口最近30分钟最近24小时
最大时间范围14天14天
行数限制必须在SQL中指定默认500条,最大10,000条

Quick Schema Reference

快速架构参考

records
table (spans and logs)

records
表(spans和logs)

Key columns for querying:
ColumnTypeDescription
start_timestamp
timestamp (UTC)When span/log was created
end_timestamp
timestamp (UTC)When span/log completed
duration
double (seconds)Time between start and end; NULL for logs
trace_id
string (32 hex)Unique trace identifier
span_id
string (16 hex)Unique span identifier
parent_span_id
string (16 hex)Parent span; NULL for root spans
span_name
stringLow-cardinality label for similar records
message
stringHuman-readable description with arguments filled in
level
integerSeverity (supports
level = 'error'
string comparison)
kind
string
span
,
log
,
span_event
, or
pending_span
service_name
stringService identifier
is_exception
booleanWhether an exception was recorded
exception_type
stringException class name
exception_message
stringException message
exception_stacktrace
stringFull traceback
attributes
JSONStructured data; query with
->>'key'
tags
string[]Grouping labels; query with
array_has(tags, 'x')
http_response_status_code
integerHTTP status code
http_method
stringHTTP method
http_route
stringHTTP route pattern
otel_status_code
stringSpan status
查询常用列:
列名类型描述
start_timestamp
timestamp (UTC)span/log的创建时间
end_timestamp
timestamp (UTC)span/log的完成时间
duration
double (seconds)起止时间间隔;logs为NULL
trace_id
string (32 hex)唯一追踪标识符
span_id
string (16 hex)唯一跨度标识符
parent_span_id
string (16 hex)父级跨度;根跨度为NULL
span_name
string同类记录的低基数标签
message
string填充参数后的可读描述信息
level
integer严重程度(支持
level = 'error'
字符串比较)
kind
string
span
log
span_event
pending_span
service_name
string服务标识符
is_exception
boolean是否记录了异常
exception_type
string异常类名称
exception_message
string异常消息
exception_stacktrace
string完整回溯信息
attributes
JSON结构化数据;使用
->>'key'
查询
tags
string[]分组标签;使用
array_has(tags, 'x')
查询
http_response_status_code
integerHTTP状态码
http_method
stringHTTP方法
http_route
stringHTTP路由模式
otel_status_code
string跨度状态

metrics
table

metrics

ColumnTypeDescription
recorded_timestamp
timestamp (UTC)When metric was recorded
metric_name
stringMetric name
metric_type
stringType (gauge, counter, histogram)
unit
stringUnit of measurement
scalar_value
doubleMetric value
service_name
stringService identifier
attributes
JSONMetric dimensions
Full schema:
references/schema.md
列名类型描述
recorded_timestamp
timestamp (UTC)指标记录时间
metric_name
string指标名称
metric_type
string类型(gauge、counter、histogram)
unit
string度量单位
scalar_value
double指标数值
service_name
string服务标识符
attributes
JSON指标维度
完整架构:
references/schema.md

SQL Syntax

SQL语法

Logfire uses Apache DataFusion (Postgres-like). Key patterns:
sql
-- Time filtering
WHERE start_timestamp > now() - interval '1 hour'

-- JSON attribute access
WHERE attributes->>'user_id' = '123'
SELECT attributes->>'http.url' as url FROM records

-- Nested JSON
attributes->'request'->>'method'

-- Array filtering
WHERE array_has(tags, 'production')

-- Level filtering (string comparison works)
WHERE level = 'error'

-- Case-insensitive matching
WHERE message ILIKE '%timeout%'

-- Time bucketing for aggregation
SELECT time_bucket(interval '5 minutes', start_timestamp) as bucket,
       count(*) FROM records GROUP BY bucket ORDER BY bucket
Logfire使用Apache DataFusion(类Postgres)。核心用法示例:
sql
-- 时间过滤
WHERE start_timestamp > now() - interval '1 hour'

-- JSON属性访问
WHERE attributes->>'user_id' = '123'
SELECT attributes->>'http.url' as url FROM records

-- 嵌套JSON
attributes->'request'->>'method'

-- 数组过滤
WHERE array_has(tags, 'production')

-- 级别过滤(支持字符串比较)
WHERE level = 'error'

-- 不区分大小写匹配
WHERE message ILIKE '%timeout%'

-- 时间分桶聚合
SELECT time_bucket(interval '5 minutes', start_timestamp) as bucket,
       count(*) FROM records GROUP BY bucket ORDER BY bucket

MCP Approach (Interactive)

MCP方式(交互式)

Call the
query_run
MCP tool:
  • query
    (required): SQL query string
  • project
    (optional): target project (default: user's current project)
  • min_timestamp
    /
    max_timestamp
    (optional): ISO timestamps for time window
Default window is last 30 min. Max range is 14 days. Always include
LIMIT
in SQL.
调用
query_run
MCP工具:
  • query
    (必填):SQL查询字符串
  • project
    (可选):目标项目(默认:用户当前项目)
  • min_timestamp
    /
    max_timestamp
    (可选):时间窗口的ISO时间戳
默认时间窗口为最近30分钟,最大范围为14天。SQL中必须包含
LIMIT

Common queries

常用查询示例

sql
-- Recent errors
SELECT start_timestamp, message, exception_type, exception_message
FROM records WHERE is_exception LIMIT 20

-- Slow spans
SELECT span_name, duration, start_timestamp
FROM records WHERE duration > 1.0 ORDER BY duration DESC LIMIT 20

-- Endpoint errors
SELECT start_timestamp, message, http_response_status_code
FROM records WHERE http_route = '/api/users' AND level = 'error' LIMIT 20

-- Full trace
SELECT span_name, message, duration, parent_span_id
FROM records WHERE trace_id = '<id>' ORDER BY start_timestamp

-- Error breakdown by service
SELECT service_name, count(*) as errors
FROM records WHERE is_exception GROUP BY service_name ORDER BY errors DESC
sql
-- 近期错误
SELECT start_timestamp, message, exception_type, exception_message
FROM records WHERE is_exception LIMIT 20

-- 慢跨度
SELECT span_name, duration, start_timestamp
FROM records WHERE duration > 1.0 ORDER BY duration DESC LIMIT 20

-- 端点错误
SELECT start_timestamp, message, http_response_status_code
FROM records WHERE http_route = '/api/users' AND level = 'error' LIMIT 20

-- 完整追踪
SELECT span_name, message, duration, parent_span_id
FROM records WHERE trace_id = '<id>' ORDER BY start_timestamp

-- 按服务统计错误
SELECT service_name, count(*) as errors
FROM records WHERE is_exception GROUP BY service_name ORDER BY errors DESC

REST API Approach (Programmatic)

REST API方式(程序化)

Endpoint:
GET https://logfire-api.pydantic.dev/v1/query
Region variants:
  • US:
    https://logfire-us.pydantic.dev/v1/query
  • EU:
    https://logfire-eu.pydantic.dev/v1/query
Auth:
Authorization: Bearer <read_token>
Parameters:
  • sql
    (required): SQL query
  • min_timestamp
    /
    max_timestamp
    (optional): ISO timestamps
  • limit
    (optional): row limit (default 500, max 10,000)
Response formats (via
Accept
header):
  • application/json
    — column-oriented JSON (default)
  • application/json
    with
    row_oriented=true
    param — row-oriented JSON
  • text/csv
    — CSV
  • application/vnd.apache.arrow.stream
    — Apache Arrow
Python clients:
LogfireQueryClient
(sync),
AsyncLogfireQueryClient
(async),
logfire.db_api
(PEP 249 / pandas).
Detailed examples:
references/client-usage.md
端点
GET https://logfire-api.pydantic.dev/v1/query
区域变体:
  • 美国:
    https://logfire-us.pydantic.dev/v1/query
  • 欧盟:
    https://logfire-eu.pydantic.dev/v1/query
认证
Authorization: Bearer <read_token>
参数
  • sql
    (必填):SQL查询语句
  • min_timestamp
    /
    max_timestamp
    (可选):ISO时间戳
  • limit
    (可选):行数限制(默认500条,最大10,000条)
响应格式(通过
Accept
头指定):
  • application/json
    — 列导向JSON(默认)
  • application/json
    +
    row_oriented=true
    参数 — 行导向JSON
  • text/csv
    — CSV格式
  • application/vnd.apache.arrow.stream
    — Apache Arrow格式
Python客户端
LogfireQueryClient
(同步)、
AsyncLogfireQueryClient
(异步)、
logfire.db_api
(符合PEP 249 / pandas兼容)。
详细示例:
references/client-usage.md

Query Best Practices

查询最佳实践

  1. Always LIMIT — start with 20, increase as needed
  2. Use
    min_timestamp
    /
    max_timestamp
    params
    for simple time windows instead of SQL
    WHERE
  3. Filter efficiently
    service_name
    ,
    span_name
    ,
    trace_id
    ,
    is_exception
    are fast filters
  4. Use
    ->>'key'
    for JSON attribute access (returns text); use
    ->
    for nested JSON objects
  5. Avoid
    SELECT *
    — select only the columns you need
  6. Max 14-day range — queries cannot span more than 14 days
  1. 始终使用LIMIT — 从20条开始,按需增加
  2. 使用
    min_timestamp
    /
    max_timestamp
    参数
    处理简单时间窗口,而非SQL的
    WHERE
    子句
  3. 高效过滤
    service_name
    span_name
    trace_id
    is_exception
    为快速过滤字段
  4. **使用
    ->>'key'
    **访问JSON属性(返回文本);使用
    ->
    访问嵌套JSON对象
  5. 避免
    SELECT *
    — 仅选择所需列
  6. 最大14天范围 — 查询时间跨度不能超过14天