温馨提示×

centos apache日志如何切割

小樊
45
2026-10-03 04:31:27
栏目: 智能运维

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

  1. logrotate(推荐)
  2. Apache 自带 rotatelogs
  3. cronolog(较少用)

下面分别说明。


一、使用 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 天)

vim /etc/logrotate.d/httpd

示例配置:

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

3. 手动测试

logrotate -d /etc/logrotate.d/httpd   # 调试
logrotate -f /etc/logrotate.d/httpd   # 强制执行

✅ 优点:系统级、稳定、无需改 Apache 配置


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

适合需要 精细控制日志格式和切割周期 的场景。

1. 修改 httpd 配置

vim /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 = 一天(秒)
  • 按大小:rotatelogs /var/log/httpd/access_log 10M

2. 重启 Apache

systemctl restart httpd

✅ 优点:实时切割
❌ 缺点:logrotate 不会再管理这些日志


三、使用 cronolog(了解即可)

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

⚠️ 目前使用较少,维护不如 logrotate 活跃


推荐方案总结

场景 推荐方式
普通 CentOS 服务器 ✅ logrotate
需要按小时/大小切 rotatelogs
老旧系统 cronolog

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

需要我帮你写一份完整的 logrotate 配置或排查日志不切割的问题吗?

0 踩