auto_explain 是一个 contrib 模块,它使 PostgreSQL 能够自动记录慢查询的执行计划。
auto_explain 在 PostgreSQL 8.4 中被添加。
变更历史
- PostgreSQL 16
- 添加了选项
auto_explain.log_parameter_max_length(提交 d4bfe412)
- 添加了选项
- PostgreSQL 12
- 添加了选项
auto_explain.log_level(提交 2d36a5e9)
- 添加了选项
- PostgreSQL 9.6
- 添加了选项
auto_explain.sample_rate以便捕获所有查询的配置比例 (提交 92f03fe7)
- 添加了选项
- PostgreSQL 9.4
- 添加了选项
auto_explain.log_trigger,它记录触发器执行时间 (提交 e2a0fc53)
- 添加了选项
- PostgreSQL 9.0
- 将查询文本添加到输出 (提交 fc5173ad)
- PostgreSQL 8.4
- 添加 (提交 e125e28e)
配置
通常,auto_explain 会被包含在 postgresql.conf 的 shared_preload_libraries 选项中,以跟踪所有数据库会话中的慢查询。超级用户也可以通过 LOAD 'auto_explain' 将其加载到单个会话中。请注意,无法为单个数据库启用 auto_explain。
使用 auto_explain 会带来一些额外的开销,并可能影响整体数据库性能。因此,应仅在需要时启用它。
默认情况下,auto_explain 在显式配置之前不会激活。至少,必须将 auto_explain.log_min_duration 设置为零(“记录所有计划”)或更大的值(要记录的语句的最小持续时间,以毫秒为单位)。有关所有配置选项的详细信息,请参阅 auto_explain 文档。配置选项只能由超级用户设置。
示例
在单个会话中启用 auto_explain
postgres=# LOAD 'auto_explain'; LOAD postgres=# SET auto_explain.log_min_duration = 0; SET postgres=# SELECT count(*) FROM pgbench_branches b JOIN pgbench_accounts a ON b.bid = a.bid; count -------- 100000 (1 row)
服务器日志将包含类似以下的输出
LOG: duration: 26.516 ms plan:
Query Text: SELECT count(*)
FROM pgbench_branches b
JOIN pgbench_accounts a ON b.bid = a.bid;
Aggregate (cost=4141.01..4141.02 rows=1 width=0)
-> Nested Loop (cost=0.00..3891.01 rows=100000 width=0)
Join Filter: (b.bid = a.bid)
-> Seq Scan on pgbench_branches b (cost=0.00..1.01 rows=1 width=4)
-> Seq Scan on pgbench_accounts a (cost=0.00..2640.00 rows=100000 width=4)
参考资料
- PostgreSQL 文档: auto_explain
