在 CentOS 上,Apache(httpd)日志切割常用 三种方式:
下面分别说明,最常用的是 logrotate。
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
}
编辑或新建:
vi /etc/logrotate.d/httpd
示例:
/var/log/httpd/access_log
/var/log/httpd/error_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 # 强制执行
编辑:
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"
按大小切割(如 100MB):
CustomLog "|/usr/sbin/rotatelogs /var/log/httpd/access_log 100M" combined
systemctl restart httpd
yum install cronolog
CustomLog "|/usr/bin/cronolog /var/log/httpd/access_%Y%m%d.log" combined
reload httpdnotifempty)restorecon -Rv /var/log/httpd
| 场景 | 推荐方式 |
|---|---|
| CentOS 标准环境 | logrotate ✅ |
| 精确按天/大小 | rotatelogs |
| 老系统兼容 | cronolog |
如果你是 CentOS 7/8 + Apache 2.4,直接用 logrotate 最省心。
需要我帮你写一份完整的 logrotate 配置或按“天 + 压缩 + 删除旧日志”的方案吗?