在 CentOS 上切割 Apache 日志,常见做法有 三种:
1️⃣ 使用 Apache 自带的 rotatelogs
2️⃣ 使用系统自带的 logrotate(最推荐)
3️⃣ 自己写脚本 + cron(不推荐,除非特殊需求)
下面按顺序说明。
CentOS 通常已经安装了 logrotate,并且 Apache 的日志切割也是用它管理的。
cat /etc/logrotate.d/httpd
典型内容示例:
/var/log/httpd/*log {
missingok
notifempty
sharedscripts
delaycompress
postrotate
/bin/systemctl reload httpd > /dev/null 2>/dev/null || true
endscript
}
daily / weekly / monthly:切割周期rotate 30:保留 30 个旧日志compress:压缩旧日志missingok:日志不存在也不报错notifempty:空日志不切割/var/log/httpd/*log {
daily
missingok
notifempty
rotate 30
compress
delaycompress
sharedscripts
postrotate
/bin/systemctl reload httpd > /dev/null 2>&1 || true
endscript
}
logrotate -d /etc/logrotate.d/httpd # 模拟执行
logrotate -f /etc/logrotate.d/httpd # 强制执行
✅ 优点:系统级、稳定、CentOS 官方推荐
适合需要 按小时/天/大小 切割,且不依赖 logrotate。
编辑:
vi /etc/httpd/conf/httpd.conf
CustomLog "|/usr/sbin/rotatelogs /var/log/httpd/access_log.%Y%m%d 86400" combined
ErrorLog "|/usr/sbin/rotatelogs /var/log/httpd/error_log.%Y%m%d 86400"
CustomLog "|/usr/sbin/rotatelogs /var/log/httpd/access_log 100M" combined
systemctl restart httpd
✅ 优点:实时切割
❌ 缺点:不会自动压缩,日志多了要自己清理
示例(每天凌晨切割):
0 0 * * * mv /var/log/httpd/access_log /var/log/httpd/access_log.$(date +%F)
systemctl reload httpd
⚠️ 容易丢日志,不建议生产环境使用。
| 场景 | 推荐方式 |
|---|---|
| CentOS 服务器 | ✅ logrotate |
| 需要精确时间切割 | rotatelogs |
| 简单测试 | cron |
如果你愿意,可以告诉我:
httpd -v)我可以帮你写一份 可直接用的配置。