温馨提示×

centos apache日志怎么切割

小樊
41
2026-09-27 07:38:02
栏目: 智能运维

在 CentOS 上,Apache(httpd)日志切割常用 三种方式:

  1. logrotate(推荐,系统自带)
  2. rotatelogs(Apache 自带)
  3. cronolog(第三方工具,较少用)

下面分别说明,最常用的是 logrotate。


一、使用 logrotate 切割(推荐 ✅)

CentOS 默认已安装 logrotate,并且通常已经有 Apache 的配置文件。

1. 查看已有配置

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. 自定义切割规则(示例:每天切割,保留 30 天)

编辑或新建:

vi /etc/logrotate.d/httpd

示例:

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

3. 手动测试

logrotate -d /etc/logrotate.d/httpd   # 调试(不真实执行)
logrotate -f /etc/logrotate.d/httpd   # 强制执行

二、使用 Apache rotatelogs(按大小/时间)

1. 修改 httpd 配置

编辑:

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"

按大小切割(如 100MB):

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

2. 重启 Apache

systemctl restart httpd

三、使用 cronolog(不推荐新环境)

安装

yum install cronolog

配置

CustomLog "|/usr/bin/cronolog /var/log/httpd/access_%Y%m%d.log" combined

四、常见问题

1. 日志不切割?

  • 是否执行了 reload httpd
  • logrotate 是否到了触发时间(默认凌晨)
  • 日志是否为空(notifempty)

2. SELinux 导致写不了日志?

restorecon -Rv /var/log/httpd

推荐方案总结

场景 推荐方式
CentOS 标准环境 logrotate ✅
精确按天/大小 rotatelogs
老系统兼容 cronolog

如果你是 CentOS 7/8 + Apache 2.4,直接用 logrotate 最省心。

需要我帮你写一份完整的 logrotate 配置或按“天 + 压缩 + 删除旧日志”的方案吗?

0 踩