在 CentOS 上清理 Apache 日志,常见做法有手动删除/截断、使用 logrotate、按时间清理等。下面按推荐程度说明。
# 查看 Apache 主配置
grep -i "ErrorLog" /etc/httpd/conf/httpd.conf
grep -i "CustomLog" /etc/httpd/conf/httpd.conf
常见日志路径:
/var/log/httpd/error_log/var/log/httpd/access_log/var/log/httpd/xxx-access_logCentOS 默认已为 Apache 配置 logrotate。
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
}
logrotate -f /etc/logrotate.d/httpd
ls -lh /var/log/httpd/
例如:
access_log
access_log-20240101
access_log-20240108.gz
# 清空访问日志
: > /var/log/httpd/access_log
# 清空错误日志
: > /var/log/httpd/error_log
✅ 不会影响 Apache 运行
rm -f /var/log/httpd/*-2023*.gz
⚠️ 不要直接 rm access_log,否则 Apache 可能继续写已删除文件(需 reload)
如果直接删除了日志文件:
systemctl reload httpd
或
apachectl graceful
编辑 logrotate 配置(示例保留 30 天):
vi /etc/logrotate.d/httpd
增加:
rotate 30
daily
然后测试:
logrotate -d /etc/logrotate.d/httpd
/var/log/httpd/*log {
size 100M
rotate 10
compress
missingok
notifempty
sharedscripts
postrotate
systemctl reload httpd
endscript
}
| 场景 | 推荐方式 |
|---|---|
| 日常维护 | logrotate |
| 磁盘爆了 | : > 日志文件 |
| 删除旧日志 | logrotate + rotate |
| 生产环境 | 不要直接 rm |
如果你愿意,可以告诉我:
我可以给你一条最合适的具体命令。