温馨提示×

apache日志centos如何轮转

小樊
34
2026-10-23 16:38:25
栏目: 智能运维

在 CentOS 上,Apache 日志(通常是 /var/log/httpd/access_log 和 /var/log/httpd/error_log)一般不是手动写脚本轮转,而是由 logrotate 管理的。下面给你完整说明。


一、CentOS 中 Apache 日志轮转机制

CentOS 使用 logrotate 来自动轮转系统日志,包括 Apache。

Apache 的 logrotate 配置文件通常在:

/etc/logrotate.d/httpd

(有些版本叫 apache、httpd 或包含在 syslog 里)


二、查看 Apache 的 logrotate 配置

执行:

cat /etc/logrotate.d/httpd

常见内容示例(CentOS 7/8):

/var/log/httpd/*log {
    missingok
    notifempty
    sharedscripts
    delaycompress
    postrotate
        /bin/systemctl reload httpd > /dev/null 2>/dev/null || true
    endscript
}

三、默认轮转规则(CentOS)

  • 频率:默认每周
  • 保留:通常 4 周
  • 压缩:旧日志会 gzip
  • 轮转后:通过 reload httpd 让 Apache 重新打开日志文件

生成文件示例:

access_log
access_log-20260118.gz
error_log
error_log-20260118.gz

四、手动测试轮转(不真正切割)

logrotate -d /etc/logrotate.d/httpd

-d = debug,只模拟,不改文件


五、手动立即轮转 Apache 日志

logrotate -f /etc/logrotate.d/httpd

⚠️ 轮转后 Apache 必须重新打开日志:

systemctl reload httpd

六、自定义 Apache 日志轮转(常用示例)

1️⃣ 每天轮转,保留 30 天

编辑:

vi /etc/logrotate.d/httpd

修改为:

/var/log/httpd/*log {
    daily
    missingok
    notifempty
    rotate 30
    compress
    delaycompress
    sharedscripts
    postrotate
        /bin/systemctl reload httpd > /dev/null 2>&1 || true
    endscript
}

2️⃣ 不压缩(某些审计需求)

nocompress

3️⃣ 按大小轮转(例如 100M)

size 100M

⚠️ 注意:如果同时写 daily 和 size,满足任一条件即轮转


七、logrotate 何时执行?

CentOS 通过 cron / systemd timer:

systemctl status logrotate.timer

或:

cat /etc/cron.daily/logrotate

八、常见问题

❓ Apache 日志不轮转?

可能原因:

  • logrotate 未运行
  • 配置路径不对
  • Apache 没 reload(日志仍写旧文件)

检查:

logrotate -d /etc/logrotate.d/httpd

❓ 轮转后日志不更新?

必须 reload:

systemctl reload httpd

九、总结(最简方案)

✅ CentOS 上 Apache 日志轮转 用 logrotate,不用自己写脚本
✅ 配置文件:/etc/logrotate.d/httpd
✅ 改完配置后测试:logrotate -d
✅ 立即生效:logrotate -f


如果你用的是 CentOS 6 / 7 / 8 / Stream,或者 Apache 是从源码安装的,可以告诉我,我可以给你更精确配置。

0 踩