Ubuntu系统中,PostgreSQL的日志文件默认存储在**/var/log/postgresql/**目录下,文件命名格式为postgresql-<version>-main.log(例如postgresql-14-main.log)。其中<version>为PostgreSQL版本号(如14、15),main表示数据库集群名称(默认集群)。
PostgreSQL的日志功能通过postgresql.conf配置文件控制,关键参数如下(位于/etc/postgresql/<version>/main/postgresql.conf):
logging_collector:是否开启日志收集(默认off)。设为on后,PostgreSQL会将日志输出到指定文件而非标准错误。log_directory:日志存储目录(默认pg_log,相对于数据目录$PGDATA)。若设为绝对路径(如/var/log/postgresql/pg_log),日志将直接存入该目录。log_filename:日志文件命名格式(支持时间变量)。常用格式如postgresql-%Y-%m-%d_%H%M%S.log(按日期和时间生成唯一文件),或postgresql-%a.log(按星期几生成,如postgresql-Mon.log)。log_rotation_age:日志文件最大存活时间(默认1d,即1天)。超过该时间的日志文件会被自动归档或删除。log_rotation_size:日志文件最大尺寸(默认0,即不限大小)。超过该尺寸的日志文件会被分割成新文件(单位:KB、MB,如100MB)。log_min_messages:日志记录级别(从低到高:debug5→debug4→debug3→debug2→debug1→info→notice→warning→error→log→fatal→panic)。生产环境建议设为warning或error,避免过多调试信息影响性能。log_min_duration_statement:记录执行时间超过该值的SQL语句(单位:毫秒,默认0,即不记录)。例如设为1000,则会记录所有执行时间超过1秒的SQL,用于慢查询分析。log_statement:记录的SQL语句类型(可选:none→ddl→mod→all)。ddl记录CREATE/ALTER/DROP等数据定义语句,mod记录ddl+INSERT/UPDATE/DELETE等数据修改语句,all记录所有SQL(生产环境慎用,会影响性能)。修改postgresql.conf后,需重启PostgreSQL服务使配置生效:
sudo systemctl restart postgresql
若需重新加载配置(无需重启),可使用:
sudo systemctl reload postgresql
使用tail命令查看最新日志(需sudo权限,因为日志文件属于postgres用户):
sudo tail -n 100 /var/log/postgresql/postgresql-14-main.log # 查看最后100行
实时监控日志(跟踪新增内容):
sudo tail -f /var/log/postgresql/postgresql-14-main.log
若不确定日志文件位置,可通过以下两种方式确认:
postgresql.conf中的log_directory和log_filename参数。sudo -u postgres psql
SHOW log_directory; # 显示日志目录(相对或绝对路径)
SHOW log_filename; # 显示日志文件名
若log_directory为相对路径(如log),完整路径为数据目录 + log_directory + log_filename(数据目录可通过SHOW data_directory;获取)。若出现“无法打开日志文件”的错误(如tail: cannot open '/var/log/postgresql/postgresql-14-main.log' for reading: No such file or directory),需检查以下两点:
ls命令确认日志文件路径是否正确(参考步骤3)。chmod添加读取权限(谨慎操作):sudo chmod 644 /var/log/postgresql/postgresql-14-main.log # 允许所有用户读取
或使用sudo运行tail命令(无需修改权限)。pgBadger是一款开源工具,可将PostgreSQL日志转换为HTML格式的详细报告,包含查询统计、慢查询分析、锁等待等信息。
sudo apt install pgbadger # Ubuntu/Debian
pgbadger /var/log/postgresql/postgresql-14-main.log -o report.html
report.html,即可查看可视化分析结果(如慢查询Top10、连接统计等)。通过log_min_duration_statement参数记录慢查询后,可使用grep命令提取慢查询日志:
cat /var/log/postgresql/postgresql-14-main.log | grep 'duration' # 查看所有慢查询记录
针对慢查询,可使用EXPLAIN ANALYZE分析查询计划,优化索引或SQL语句:
EXPLAIN ANALYZE SELECT * FROM orders WHERE customer_id = 12345; # 分析查询性能
若customer_id列无索引,可创建索引加速查询:
CREATE INDEX idx_orders_customer_id ON orders(customer_id); # 创建索引