You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

AWS Linux中/etc/cron.daily无法执行logrotate的问题求助

排查Nginx Logrotate每日轮转不生效的问题

我来帮你一步步定位这个logrotate不生效的问题哈,以下是几个常见的排查方向和解决方案:

1. 先验证Logrotate配置本身是否正确

直接用调试模式运行logrotate,不实际执行轮转,只输出过程和错误:

logrotate -d /etc/logrotate.d/nginx

仔细看输出内容,如果有语法错误、日志路径不存在、权限不足等问题,这里会明确提示。比如如果你的nginx日志路径写的是/var/log/nginx/access.log但实际路径是/var/log/nginx/www.access.log,就会报错找不到文件。

2. 检查Cron.daily里的Logrotate脚本权限

确保/etc/cron.daily/logrotate是可执行的,执行命令查看权限:

ls -l /etc/cron.daily/logrotate

如果权限里没有x(可执行),就给它加上:

chmod +x /etc/cron.daily/logrotate

3. 确认Anacron的运行状态与时间戳

因为系统通常用anacron来执行daily级别的任务,先检查anacron是否在运行:

systemctl status anacron

如果是non-systemd系统,可以用service anacron status。另外,/var/spool/anacron/cron.daily是anacron记录上次执行时间的文件,如果这个文件的日期是当天,anacron会认为已经执行过任务了。可以手动删除这个文件,然后重新触发:

rm /var/spool/anacron/cron.daily
run-parts /etc/cron.daily

4. 手动执行Logrotate看是否生效

如果调试模式没问题,试试直接执行logrotate命令看能不能轮转日志:

logrotate /etc/logrotate.d/nginx

如果这个命令能成功生成access.log-20180222这类文件,说明问题出在cron/anacron的调度上,而不是logrotate配置本身。

5. 检查Nginx日志文件的权限

确保logrotate(通常以root用户运行)能读写nginx的日志文件。比如查看日志文件权限:

ls -l /var/log/nginx/access.log

如果日志文件属主是nginx用户,权限是0600,可以在logrotate配置里添加su nginx nginx,让logrotate切换到nginx用户执行轮转,避免权限问题。

6. 查看Logrotate的执行日志

系统通常会把logrotate的运行日志记录在/var/log/syslog或/var/log/messages里,搜索关键词logrotate:

grep logrotate /var/log/syslog

这里会显示每次执行的结果,如果有失败原因,比如“failed to open log file”,就能快速定位问题。

附:标准的Nginx Logrotate配置示例

如果你的配置有遗漏,参考这个完整的配置:

/var/log/nginx/*.log {
    daily
    missingok
    rotate 14
    compress
    delaycompress
    notifempty
    create 0640 nginx nginx
    sharedscripts
    postrotate
        if [ -f /var/run/nginx.pid ]; then
            kill -USR1 `cat /var/run/nginx.pid`
        fi
    endscript
}

重点说明:

  • postrotate块里的kill -USR1是关键,它会通知nginx重新打开日志文件,否则nginx会继续往旧的轮转文件里写内容,导致你看不到新的日志文件生效。
  • delaycompress会延迟压缩日志,确保nginx不再写入旧文件后再压缩,避免日志丢失。

内容的提问来源于stack exchange,提问作者Jade Han

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 09:38:21