Nginx 本身不支持 error_log 按大小轮转,必须依赖 logrotate 配合 USR1 信号实现;需统一 error_log 路径、配置 size 和 postrotate 发送 USR1、确保 pid 路径正确及权限设置。

Nginx 本身不支持对 error_log 按大小轮转,这是关键前提。error_log 指令仅接受文件路径和日志级别(如 error、warn),没有内置的 size-based rotation 参数。它不像 access_log 那样可配合 log_format 和外部工具灵活控制写入行为。
真正实现 error_log 按大小轮转,必须依赖 Linux 系统级日志管理工具 logrotate,并配合 Nginx 的信号机制(USR1)确保新日志文件被正确接管。
以下是具体操作步骤:
确认 error_log 路径明确且统一
检查 Nginx 主配置(通常是 /etc/nginx/nginx.conf 或 /usr/local/nginx/conf/nginx.conf):
error_log /var/log/nginx/error.log warn;
确保所有 error_log 指令都指向同一路径(避免多路径导致 logrotate 漏配)。若使用多个虚拟主机且各自定义了 error_log,需在 logrotate 配置中全部列出或统一收口到一个文件。
配置 logrotate 按大小切割 error.log
编辑 /etc/logrotate.d/nginx(或新建),内容如下:
/var/log/nginx/error.log {
size 100M # 达到 100MB 即触发轮转(可调,最小单位为 KB,如 50M、200M)
daily # 同时兼容时间维度(二者满足其一即执行)
rotate 30 # 保留最近 30 个归档文件
compress # 自动 gzip 压缩旧日志(生成 .gz)
delaycompress # 延迟压缩:本次轮转不压,下次才压上一次的
missingok # 日志文件不存在时不报错
notifempty # 文件为空时不轮转
create 640 nginx nginx # 创建新 error.log,权限 640,属主属组 nginx
sharedscripts
postrotate
if [ -f /var/run/nginx.pid ]; then
kill -USR1 `cat /var/run/nginx.pid`
elif [ -f /usr/local/nginx/logs/nginx.pid ]; then
kill -USR1 `cat /usr/local/nginx/logs/nginx.pid`
fi
endscript
}⚠️ 注意:
-
size和daily可共存,logrotate 会检查「上次轮转后是否满 size」或「是否已过一天」,任一成立即执行; -
USR1信号通知 Nginx 重新打开日志文件,这是保证日志不丢失的核心步骤; -
postrotate中的 pid 路径需与你实际 Nginx 启动时指定的pid路径一致(可通过nginx -t -v或ps aux | grep nginx查看)。
验证配置并手动触发测试
# 语法检查(无输出即正常) sudo logrotate -d /etc/logrotate.d/nginx # 强制执行一次(立即轮转,无视 size/daily 条件) sudo logrotate -f /etc/logrotate.d/nginx # 查看结果 ls -lh /var/log/nginx/error* # 应看到 error.log(新空文件)、error.log.1(原内容)、error.log.1.gz(若 compress 生效)
确保 cron 自动运行
logrotate 默认由系统 cron.daily 每日凌晨运行,无需额外加 crontab。但可确认:
ls /etc/cron.daily/logrotate # 正常应存在
如需更频繁(例如每小时检查大小),可单独添加 cron 任务:
# 编辑 root crontab sudo crontab -e # 添加一行(每小时检查一次,适合高错误率场景) 0 * * * * /usr/sbin/logrotate -s /var/lib/logrotate/status /etc/logrotate.d/nginx 2>/dev/null
注意:加 -s 显式指定状态文件路径,避免与 daily 任务冲突。
Nginx 错误日志按大小轮转,本质是 logrotate 主动监控 + Nginx 被动响应的协作过程。只要路径对得准、USR1 发得准、权限设得对,就能稳定运行。


















