DBAtlas · 数据库运维图谱

使用 auto_explain 记录慢查询的执行计划

PostgreSQL性能

命令

-- 1) Per session: effective immediately, no restart (superuser)
LOAD 'auto_explain';
SET auto_explain.log_min_duration = '500ms';
SET auto_explain.log_analyze = on;
SET auto_explain.log_buffers = on;
SET auto_explain.log_timing = off;
SET auto_explain.log_nested_statements = on;

-- 2) Persistent: loaded by new sessions, a reload is enough.
--    The module must be LOADed in this session before ALTER SYSTEM accepts auto_explain.* parameters.
LOAD 'auto_explain';
ALTER SYSTEM SET session_preload_libraries = 'auto_explain';
ALTER SYSTEM SET auto_explain.log_min_duration = '2s';
ALTER SYSTEM SET auto_explain.log_analyze = on;
ALTER SYSTEM SET auto_explain.log_buffers = on;
ALTER SYSTEM SET auto_explain.log_timing = off;
ALTER SYSTEM SET auto_explain.sample_rate = 0.1;
SELECT pg_reload_conf();

作用

将超过阈值的查询执行计划写入服务器日志(log_analyze 开启时附带实际行数和缓冲区数据);捕获以应用真实参数生成的计划。

适用场景

当查询只在应用中或使用特定参数时才变慢,且无法用手动 EXPLAIN 重现时;用于捕获间歇性的计划变化。

注意

log_analyze = on 会给每个被采样的查询增加插桩开销,包括低于阈值的查询;log_timing = off 和 sample_rate < 1 可降低开销。在生产环境中 log_min_duration = 0 会刷爆日志。ALTER SYSTEM SET session_preload_libraries 会覆盖现有值;请先检查 SHOW session_preload_libraries。session_preload_libraries 不影响现有会话;要在每个进程中加载,需要 shared_preload_libraries 加重启。

在 DBAtlas 中打开 →

相关内容