在 CentOS 上,Apache 日志过大是常见问题,一般可以从日志切割、清理、限制大小、调整日志级别几个方面解决。
CentOS 默认已安装 logrotate,Apache 通常已有配置文件:
/etc/logrotate.d/httpd
vi /etc/logrotate.d/httpd
示例(推荐):
/var/log/httpd/*log {
daily
missingok
notifempty
rotate 14
compress
delaycompress
sharedscripts
postrotate
/bin/systemctl reload httpd > /dev/null 2>&1 || true
endscript
}
说明:
daily:每天切割rotate 14:保留 14 天compress:压缩旧日志reload httpd:避免日志写错文件logrotate -d /etc/logrotate.d/httpd # 测试(不真实执行)
logrotate -f /etc/logrotate.d/httpd # 强制执行
⚠️ 不要直接 rm 正在写入的日志
正确方式:
# 清空日志(Apache 仍可继续写)
>: /var/log/httpd/access_log
>: /var/log/httpd/error_log
或:
truncate -s 0 /var/log/httpd/access_log
编辑 Apache 配置:
vi /etc/httpd/conf/httpd.conf
示例:
# 关闭默认访问日志(不推荐生产,但可针对某些虚拟主机)
# CustomLog logs/access_log combined
减少记录字段,例如不记录静态文件:
SetEnvIf Request_URI "\.(jpg|png|css|js)$" static
CustomLog logs/access_log combined env=!static
Apache 本身不能直接限制日志大小,必须依赖:
logrotatecron + scriptCustomLog "|/usr/sbin/rotatelogs /var/log/httpd/access_log 86400" combined
86400 = 1 天du -sh /var/log/httpd/*
✅ 生产环境:logrotate(daily + compress + 14 天)
✅ 高访问量:过滤静态资源日志
✅ 紧急处理:truncate 清空,不 rm
如果你愿意,可以贴一下:
我可以帮你写一份针对性配置。