apache日志按天轮转主流有三种方式:cronolog实现严格零点切分,rotatelogs为apache原生工具按周期滚动,logrotate是系统级外部轮转并支持压缩清理。

Apache 日志按天自动轮转切割,主流有三种可靠方式:使用 cronolog、rotatelogs(Apache 自带)或系统级工具 logrotate。三者定位不同——前两者在 Apache 进程内实时切分,logrotate 是外部定时轮转。选哪种,取决于你是否需要“严格按日界线(00:00)切分”、是否已安装依赖、以及运维习惯。
cronolog:简单直接,适合轻量部署
它通过管道接收 Apache 日志流,按时间格式动态生成文件名,零点自动切换,不依赖外部定时任务。
- 修改 Apache 配置(如 /etc/httpd/conf/httpd.conf 或 /etc/httpd/conf.d/logging.conf):
CustomLog "|/usr/bin/cronolog /var/log/httpd/access_%Y%m%d.log" combinedErrorLog "|/usr/bin/cronolog /var/log/httpd/error_%Y%m%d.log" - 确认 /var/log/httpd/ 目录存在,且 Apache 运行用户(如 apache 或 www-data)有写权限
- 用 which cronolog 核对路径,若不在 /usr/bin/,请替换为实际路径
- 重载配置:systemctl reload httpd,当日就会生成类似 access_20260729.log 的文件,次日零点起自动写入新文件
rotatelogs:Apache 原生支持,无需额外安装
它是 mod_log_config 模块配套工具,默认随 Apache 安装,路径通常为 /usr/sbin/rotatelogs 或 /usr/local/apache2/bin/rotatelogs。
PyCharm 2026.2.0.1 Linux版提供 JetBrains 官方 2026.2.0.1 版本安装包,适合需要指定 PyCharm 版本进行 Python 项目开发、运行和调试的用户。
- 配置示例:
CustomLog "|/usr/sbin/rotatelogs /var/log/httpd/access_%Y%m%d.log 86400" combinedErrorLog "|/usr/sbin/rotatelogs /var/log/httpd/error_%Y%m%d.log 86400" - 86400 表示每 86400 秒(即 1 天)滚动一次;也可加时区偏移(如 480 表示东八区),但非必需
- 注意:rotatelogs 不保证严格 00:00 切分,而是从首次启动后第 86400 秒开始滚动,后续周期性执行。若需精准按日界线切,建议配合 cronolog 或 logrotate
- 确保 mod_log_config 已启用(一般默认开启)
logrotate:系统级管理,兼顾归档压缩与清理
它不干预 Apache 写日志过程,而是在每天固定时间扫描并轮转已有日志文件,更适合统一管理多服务日志,并支持压缩、保留份数、自动清理等策略。
- 新建配置文件:/etc/logrotate.d/httpd,内容如下:
/var/log/httpd/access.log /var/log/httpd/error.log {<br> daily<br> missingok<br> rotate 7<br> compress<br> delaycompress<br> notifempty<br> create 0644 apache apache<br> sharedscripts<br> postrotate<br> /bin/systemctl reload httpd > /dev/null 2>/dev/null || true<br> endscript<br>} - 关键点:
— daily 表示每天检查是否满 1 天(触发依赖 /etc/cron.daily/logrotate)
— create 0644 apache apache 确保新日志权限和属主匹配 Apache 进程
— postrotate 中 reload 是为了通知 Apache 重新打开日志文件(避免继续写入已轮转的旧文件) - 手动测试轮转:logrotate -f /etc/logrotate.d/httpd
不复杂但容易忽略:无论用哪种方式,都要确认 Apache 进程对目标目录有写权限;若启用了 SELinux(RHEL/CentOS),可能需调整上下文或临时禁用验证;首次配置后务必 reload 而非 restart,避免服务中断。









