温馨提示×

centos apache日志怎么轮转

小樊
43
2026-09-21 10:04:46
栏目: 智能运维

在 CentOS 上,Apache 日志的轮转通常是通过 logrotate 来完成的,而不是 Apache 自己处理。下面给你讲清楚原理和常见做法。


一、Apache 日志轮转原理(CentOS)

CentOS 中:

  • Apache 日志一般在:/var/log/httpd/
  • 日志轮转由 logrotate 管理
  • 相关配置文件:
    • /etc/logrotate.conf(全局)
    • /etc/logrotate.d/httpd(Apache 专用)

二、默认的 Apache 日志轮转配置

CentOS 安装 httpd 后,会自动生成:

/etc/logrotate.d/httpd

内容大致如下(简化):

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

关键点说明

  • reload httpd:让 Apache 重新打开日志文件(必须,否则还写旧文件)
  • delaycompress:先不压缩,下一次再压
  • 默认按 周 或 大小 轮转(取决于系统)

三、常见轮转策略修改

1️⃣ 按大小轮转(推荐大流量站点)

/var/log/httpd/*log {
    size 100M
    rotate 10
    missingok
    notifempty
    compress
    delaycompress
    sharedscripts
    postrotate
        systemctl reload httpd
    endscript
}

含义:

  • 日志超过 100M 就轮转
  • 保留 10 个历史文件

2️⃣ 按天轮转

/var/log/httpd/*log {
    daily
    rotate 30
    missingok
    notifempty
    compress
    delaycompress
    sharedscripts
    postrotate
        systemctl reload httpd
    endscript
}

四、手动测试 logrotate(很重要)

查看配置是否生效

logrotate -d /etc/logrotate.d/httpd

强制立即轮转

logrotate -f /etc/logrotate.d/httpd

五、如果使用 rotatelogs(Apache 自带)

有些人在 httpd.conf 里这样写:

CustomLog "|/usr/sbin/rotatelogs /var/log/httpd/access_log 86400" combined

✅ 这种 不需要 logrotate ❌ 但管理不如 logrotate 统一


六、常见坑

  1. 轮转后日志不写新文件

    • 原因:没 reload httpd
    • 解决:postrotate 里 reload
  2. SELinux 导致写不了

    restorecon -Rv /var/log/httpd
    
  3. 日志权限问题

    • 确保属主是 root:root 或 apache

七、总结(推荐方案)

✅ CentOS + Apache 最佳实践

  • 用 /etc/logrotate.d/httpd
  • 使用 systemctl reload httpd
  • 按大小或天轮转
  • 不混用 rotatelogs

如果你愿意,我可以:

  • 帮你写一份 生产环境 Apache 日志轮转配置
  • 或针对 CentOS 7 / 8 / Stream 给具体版本方案

0 踩