在 Ubuntu 上,Apache 的日志轮转一般是通过 logrotate 来管理的,不需要手动写脚本。下面给你说清楚原理和常见做法。
Ubuntu 下 Apache(通常是 apache2)的日志轮转由 logrotate 管理:
/etc/logrotate.d/apache2/var/log/apache2/access.logerror.loglogrotate 一般每天由 cron / systemd timer 自动执行。
/etc/logrotate.d/apache2 内容类似:
/var/log/apache2/*.log {
daily
missingok
rotate 14
compress
delaycompress
notifempty
create 640 root adm
sharedscripts
postrotate
if invoke-rc.d apache2 status > /dev/null 2>&1; then
invoke-rc.d apache2 reload > /dev/null 2>&1
fi
endscript
}
daily:每天轮转rotate 14:保留 14 个旧日志compress:压缩旧日志(.gz)delaycompress:延迟一次压缩notifempty:日志为空不轮转postrotate:轮转后 reload Apache(重要)logrotate -d /etc/logrotate.d/apache2
logrotate -f /etc/logrotate.d/apache2
ls -lh /var/log/apache2/
你应该会看到:
access.log
access.log.1
error.log
error.log.1.gz
检查:
systemctl status logrotate.timer
或
cat /etc/cron.daily/logrotate
确保 postrotate 中有 reload:
invoke-rc.d apache2 reload
或
systemctl reload apache2
如果你在 Apache 中用了:
CustomLog "|/usr/bin/rotatelogs ..."
那就 不需要 logrotate,由 Apache 自己管理。
/var/log/apache2/*.log {
weekly
rotate 8
compress
delaycompress
notifempty
create 640 root adm
sharedscripts
postrotate
systemctl reload apache2 > /dev/null 2>&1
endscript
}
✅ Ubuntu Apache 日志轮转 标准做法:
logrotate/etc/logrotate.d/apache2如果你愿意,可以贴一下你的:
rotatelogs我可以帮你定制一份配置。