CentOS 上 Apache 日志的存储与轮转策略
一 核心策略概览
- 日志写入位置与类型:访问日志通常为 /var/log/httpd/access_log,错误日志为 /var/log/httpd/error_log;格式常用 combined(信息更全)或 common(更精简)。
- 轮转机制:默认由 logrotate 按日轮转,常见保留 7 天、启用 gzip 压缩,并在轮转后通过 postrotate 发送 SIGHUP/reload 让 httpd 重新打开日志文件,避免日志句柄占用旧文件。
- 运行方式:logrotate 通常由 /etc/cron.daily/logrotate 每日定时执行,无需人工干预。
- 日志级别:通过 LogLevel 控制记录细粒度,生产环境常用 warn/error 以降低日志量。
- 扩展能力:除 logrotate 外,也可使用 rotatelogs/cronolog 在 Apache 内部按时间切分日志,实现“边写边切”。
二 默认与推荐配置
- 推荐的 logrotate 配置(/etc/logrotate.d/httpd 或 apache2)
/var/log/httpd/*.log {
daily # 按天轮转
missingok # 日志缺失不报错
rotate 7 # 保留 7 份历史
compress # 压缩旧日志
delaycompress # 延迟压缩,便于最近一份可快速查看
notifempty # 空文件不轮转
create 0640 root adm # 新建日志权限与属主属组
sharedscripts
postrotate
# 仅当 httpd 在运行时才 reload,避免失败报错
if /usr/bin/systemctl is-active --quiet httpd; then \
/usr/bin/systemctl reload httpd >/dev/null 2>&1 || true; \
fi
endscript
}
- 说明
- 使用 delaycompress 可避免刚轮转出的日志立即被压缩,便于故障排查。
- 使用 systemctl 的 reload 更适配 systemd 管理的 CentOS 环境。
- 若需更激进的留存,可将 rotate 调整为 14/30 等;若磁盘紧张,可改为 weekly 或缩短保留天数。
三 验证与运维要点
- 手动触发与回放测试:
- 测试配置与语法:logrotate -d /etc/logrotate.d/httpd(干跑)
- 强制执行一次:logrotate -f /etc/logrotate.d/httpd
- 查看轮转结果:ls -lh /var/log/httpd/;检查是否生成 .gz 历史文件。
- 实时查看与排查:tail -f /var/log/httpd/access_log;配合 grep、awk、lnav 做快速分析。
- 定时任务确认:cat /etc/cron.daily/logrotate,确保每日自动执行。
四 可选方案与扩展
- 内置时间切分(不依赖 logrotate):
- 使用 rotatelogs:
- 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”
- 使用 cronolog:
- CustomLog “|/usr/local/sbin/cronolog /var/log/httpd/%Y/%m/%d/access_log” combined
- 远程集中与合规:
- 通过 rsyslog 将日志转发至 Logstash/ELK,并可基于 TLS 加密与模板定制(如 JSON),满足审计与集中化存储需求。
- 日志瘦身与治理:
- 适度使用 LogLevel warn/error;必要时选用 common 格式;对包含 PII 的字段进行脱敏后再写入或传输。