日志文件定位
日志默认存放在 /var/log/postgresql/ 目录,文件名格式为 postgresql-{版本号}-{main/instance_name}.log。
基础配置
/etc/postgresql/{版本}/main/postgresql.conf:
logging_collector = on。log_directory = 'pg_log',log_filename = 'postgresql-%Y-%m-%d_%H%M%S.log'。log_min_messages = warning(生产环境建议)。systemctl restart postgresql。日志轮转管理
logrotate 工具(默认配置文件 /etc/logrotate.d/postgresql):/var/log/postgresql/*.log {
daily rotate 7 compress missingok notifempty
}
表示每天轮转,保留7天压缩日志。log_rotation_age(按时间,如1d)和 log_rotation_size(按大小,如100MB)控制轮转。日志分析与监控
tail -f postgresql-*.log。grep 'ERROR' postgresql-*.log。pgBadger:生成可视化报告,分析慢查询、错误日志等。ELK Stack:用于大规模日志的集中存储与分析。高级策略
rsync)将旧日志归档到远程存储。log_min_duration_statement 记录慢查询(如设为1000ms),结合 EXPLAIN ANALYZE 分析执行计划。参考来源: