CentOS 7.9 上 logrotate 每天切 nginx 日志,access.log 切出去之后原文件还在长,新文件一直是 0 字节,/etc/logrotate.d/nginx 里 postrotate 调 kill -USR1 的语句返回 1。

把日志和配置对完,能解释这个现象的基本就这几处。postrotate 脚本里用了 su 或 sudo,切换用户那一步直接失败;脚本里的路径写错,sh 找不到命令就返回非零;sharedscripts 没开,多个日志文件时脚本执行次数不对;create 指定的属主和 nginx 实际运行用户不一致,新文件写不进去。

手动跑一次看具体报错

logrotate -d -f /etc/logrotate.d/nginx 2>&1 | tail -20

随后确认 nginx 的 pid 文件在哪

cat /run/nginx.pid && grep -n 'pid' /etc/nginx/nginx.conf

然后改成用 systemctl 重开日志

printf '%s
' 'postrotate' '    /bin/systemctl reload nginx >/dev/null 2>&1 || true' 'endscript' >> /etc/logrotate.d/nginx

强制切一次并核对文件

logrotate -f /etc/logrotate.d/nginx && ls -l /var/log/nginx/

命令输出我都留了记录,免得改完记不清原来的值。

改之前先确认了最近有没有人动过配置,避免白查一遍。

别只看报错消失,验证要多做一步。access.log 重新从 0 开始增长,切出去的旧文件不再被写入,lsof 里 nginx 指向的是新文件。

kill -USR1 最轻量但 pid 路径必须对;postrotate 失败 logrotate 不会中断,只留一条 error,平时要盯它的执行记录。监控比日志更早给出信号,事后回看经常能提前半小时发现异常。

作者 9823189