用 SQL 查询日志
本指南讲解了如何使用 ClickHouse SQL 查询项目日志。可使用 MCP 或 管理 API 进行程序化访问,或者在 Studio 中使用 Explorer。如果不使用 SQL 过滤事件,可以使用 Studio 中的 日志。
🌐 This guide explains how to query project logs with ClickHouse SQL. Use MCP or the Management API for programmatic access, or Explorer in Studio. To filter events without SQL, use Logs in Studio.
查询事件 #
🌐 Query events [#querying-with-the-logs-explorer]
每个事件都是 logs 中的一行。使用 source 选择一个服务,使用限定的时间范围,并限制返回的行数。例如,以下查询返回指定时间范围内的最新 API 服务器错误:
🌐 Every event is a row in logs. Select a service with source, use a bounded time range, and limit the returned rows. For example, this query returns the latest API server errors within the supplied time range:
-- recent API server errorsselect timestamp, id, toInt32OrZero(log_attributes['response.status_code']) as status, log_attributes['request.path'] as pathfrom logswhere source = 'edge_logs' and toInt32OrZero(log_attributes['response.status_code']) between 500 and 599order by timestamp desclimit 100;使用返回的时间戳、ID、状态和路径来调查事件。没有行表示在该时间窗口内没有匹配的记录事件;在得出没有错误的结论之前,请检查来源、筛选条件和保留策略。
🌐 Use the returned timestamp, ID, status, and path to investigate an event. No rows means no matching recorded events in that window; check the source, filters, and retention before concluding that there were no errors.
MCP #
将 Supabase MCP 与 project_ref 和 read_only=true 连接。使用工具的输入模式,用 SQL 和明确的时间范围调用 query_logs。使用 execute_sql 进行 Postgres 数据库诊断,而不是 ClickHouse 日志。
🌐 Connect Supabase MCP with project_ref and read_only=true. Call query_logs with the SQL and an explicit time range, using the tool's input schema. Use execute_sql for Postgres database diagnostics, not ClickHouse logs.
管理 API #
🌐 Management API [#api]
将 SUPABASE_ACCESS_TOKEN 设置为允许读取项目日志的管理 API 访问令牌,将 PROJECT_REF 设置为项目引用。将 START 和 END 设置为 UTC 时间戳,例如 2026-09-07T09:00:00Z,范围为 24 小时或以内。将上面的查询保存为 logs.sql,然后运行:
🌐 Set SUPABASE_ACCESS_TOKEN to a Management API access token authorized to read project logs, and PROJECT_REF to the project reference. Set START and END to UTC timestamps such as 2026-09-07T09:00:00Z, with a range of 24 hours or less. Save the query above as logs.sql, then run:
curl --get "https://api.supabase.com/v1/projects/$PROJECT_REF/analytics/endpoints/logs" \ --header "Authorization: Bearer $SUPABASE_ACCESS_TOKEN" \ --data-urlencode "sql@logs.sql" \ --data-urlencode "iso_timestamp_start=$START" \ --data-urlencode "iso_timestamp_end=$END"在解释结果之前,先检查 HTTP 状态和响应中的查询错误。如果没有 sql,这个端点仅查询 API Gateway 事件。有关请求和响应字段,请参见 日志端点参考。
🌐 Inspect both the HTTP status and the response for query errors before interpreting the results. Without sql, this endpoint queries API Gateway events only. See the logs endpoint reference for request and response fields.
探索者 #
🌐 Explorer [#studio]
- 打开 资源管理器 并选择 运行 SQL。
- 打开查询源菜单并选择 日志。
- 在那个菜单里选择时间范围。
- 输入查询并选择 运行。
选定的范围会应用到查询中。日志查询来源选择 ClickHouse;source = 'edge_logs' 在其中选择 API 网关事件。当运行 Postgres SQL 时,改为选择 数据库。
🌐 The selected range is applied to the query. The Logs query source chooses ClickHouse; source = 'edge_logs' chooses API Gateway events within it. Select Database instead when running Postgres SQL.
终端访问 #
🌐 Terminal access [#cli]
Supabase CLI 不会查询 ClickHouse 日志。请使用上面的管理 API 命令。要查看实时数据库统计信息,请使用 supabase inspect db。
🌐 The Supabase CLI does not query ClickHouse logs. Use the Management API command above. For live database statistics, use supabase inspect db.
来源和字段 #
🌐 Sources and fields [#logs-explorer]
使用 日志源和字段参考 来选择服务和查询表达式。API 网关事件和服务自身的日志描述了请求的不同层次。
🌐 Use the Log sources and fields reference to choose the service and query expressions. API Gateway events and a service's own logs describe different layers of a request.
阅读结构化字段 #
🌐 Read structured fields [#understanding-field-references]
用括号方式读取地图键,同时保留其完整的点路径。log_attributes中的值是字符串。在比较之前先将数值类型转换。toInt32OrZero将缺失或非数值的值视为零;不要把这个零当作实际测量的状态或持续时间。
🌐 Read a map key with bracket access, retaining its full dotted path. Values in log_attributes are strings. Cast numeric values before comparing them. toInt32OrZero treats missing or non-numeric values as zero; do not interpret that zero as a measured status or duration.
当某个字段缺失或不熟悉时,查看已记录事件中存在的键:
🌐 When a field is missing or unfamiliar, discover the keys present on recorded events:
-- discover Postgres attributesselect arrayJoin(mapKeys(log_attributes)) as key, count() as eventsfrom logswhere source = 'postgres_logs'group by keyorder by events desclimit 100;时间范围 #
🌐 Time ranges [#timestamp-display-and-behavior]
timestamp 是一个 UTC DateTime64 值。可以直接比较和排序。Explorer 会提供所选的时间范围;MCP 和 API 调用者必须提供他们自己的有限范围。要通过 API 比较超过 24 小时的数据,需要在保留期内获取多个单独的时间窗口并合并它们的汇总。
搜索消息 #
🌐 Search messages [#filtering-with-regular-expressions]
使用 ilike 来进行不区分大小写的子字符串搜索,或者使用 ClickHouse 的 match 来进行正则表达式搜索:
🌐 Use ilike for a case-insensitive substring, or ClickHouse's match for a regular expression:
-- find connection failuresselect timestamp, id, event_messagefrom logswhere source = 'postgres_logs' and event_message ilike '%connection%' and match(event_message, '(?i)failed|refused|timeout')order by timestamp desclimit 100;将 and、or 和 not 的谓词结合起来。只选择调查所需的字段。要关联来源,请使用两者都存在的标识符;仅共享时间戳并不能说明事件属于同一个请求。
🌐 Combine predicates with and, or, and not. Select only the fields needed for the investigation. To correlate sources, use an identifier present in both; a shared timestamp alone does not establish that events belong to the same request.
按 Postgres 错误代码过滤 #
🌐 Filter by Postgres error code [#sqlstate-filtering]
通过 SQLSTATE 对 postgres_logs 进行过滤,以显示特定类别的错误,而不是按消息文本。代码存在于 log_attributes['parsed.sql_state_code']。
🌐 Filter postgres_logs by SQLSTATE to surface errors at a specific category rather than by message text. The code lives in log_attributes['parsed.sql_state_code'].
查看在一段时间内出现了哪些错误代码:
🌐 To see which error codes are occurring across a time window:
select log_attributes['parsed.sql_state_code'] as sqlstate, count() as occurrencesfrom logswhere source = 'postgres_logs' and log_attributes['parsed.sql_state_code'] != ''group by sqlstateorder by occurrences desclimit 50;在平台级别的故障期间(例如数据库进入只读模式),像 25006(read_only_sql_transaction)和 53100(disk_full)这样的代码会主导结果。如果想在平台故障期间专注于应用错误,请排除已知的平台代码:
🌐 During a platform-level incident (such as the database entering read-only mode), codes like 25006 (read_only_sql_transaction) and 53100 (disk_full) will dominate the results. To focus on application errors while a platform incident is active, exclude the known platform codes:
select timestamp, log_attributes['parsed.sql_state_code'] as sqlstate, event_messagefrom logswhere source = 'postgres_logs' and log_attributes['parsed.sql_state_code'] not in ('25006', '53100', '57P03') and log_attributes['parsed.error_severity'] = 'ERROR'order by timestamp desclimit 50;以 25 或 53 开头的 SQLSTATE 代码通常表示平台级资源事件,而不是应用错误。有关更多信息,请参见 PostgREST 错误代码参考 和 数据库大小指南。
🌐 SQLSTATE codes starting with 25 or 53 usually indicate platform-level resource events rather than application bugs. See the PostgREST error codes reference and Database size guide for context.
查询限制 #
🌐 Query limits [#limit-and-result-row-limitations]
使用明确的 limit 和较窄的时间范围。日志查询界面不接受 select * 和 count(*);列出列并使用 count()。结果限制的是返回的行数,而不是扫描的时间范围。
🌐 Use an explicit limit and narrow time range. The logs query surface rejects select * and count(*); list columns and use count(). A result limit bounds returned rows, not the time range scanned.
记录更多事件 #
🌐 Record additional events [#working-with-api-logs]
关于 HTTP 头捕获,请参见 Captured HTTP headers。事件记录的配置与查询是分开的:
🌐 For HTTP header capture, see Captured HTTP headers. Configure event recording separately from querying:
Postgres 连接 #
🌐 Postgres connections [#logging-postgres-connections]
请参阅 配置连接日志。
🌐 See Configure connection logging.
Postgres 语句 #
🌐 Postgres statements [#logging-postgres-queries]
请参阅 配置语句日志。
🌐 See Configure statement logging.
语句类别 #
🌐 Statement classes [#configuring-pgauditlog]
请查看 pgAudit 配置 了解会话和角色范围。
🌐 See pgAudit configuration for session and role scope.
实时连接 #
🌐 Realtime connections [#logging-realtime-connections]
查看 配置实时日志。
🌐 See Configure Realtime logging.