温馨提示×

apache日志分割centos怎样做

小樊
43
2026-10-09 01:06:59
栏目: 智能运维

在 CentOS 上对 Apache(httpd)日志进行分割,常见有下面几种做法,从“最推荐”到“传统方案”给你说明。


一、推荐方式:使用 logrotate(CentOS 自带,最省心)

CentOS 默认已安装 logrotate,不需要额外写脚本。

1. 查看 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
}

2. 默认分割策略

  • 每天或每周分割(取决于配置)
  • 自动压缩(.gz)
  • 自动删除旧日志(通常保留 4 周)

3. 手动测试(不真正切割)

logrotate -d /etc/logrotate.d/httpd

4. 强制立即切割

logrotate -f /etc/logrotate.d/httpd

✅ 生产环境推荐这种方式


二、Apache 自带:rotatelogs(按大小/时间切割)

适合 不想用 logrotate 的场景。

示例:按天切割

编辑:

vi /etc/httpd/conf/httpd.conf

修改日志配置:

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"

说明:

  • 86400 = 一天(秒)
  • 日志文件会变成:
    access_log.20260121
    

重启 Apache:

systemctl restart httpd

三、按大小切割(rotatelogs)

例如:每 100MB 切一次

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

四、常见坑提醒

1. SELinux 问题

如果日志写不进去:

ls -Z /var/log/httpd
restorecon -Rv /var/log/httpd

2. 切割后不生效

一定是 未 reload Apache

  • logrotate 里必须有:
postrotate
    systemctl reload httpd
endscript

五、如何选择?

场景 推荐
服务器常规使用 ✅ logrotate
容器 / 特殊环境 rotatelogs
按大小严格限制 rotatelogs

如果你愿意,可以告诉我:

  • Apache 版本(httpd -v)
  • 日志路径
  • 想按 天 / 大小 / 保留天数

我可以直接帮你写一份 可用配置。

0 踩