温馨提示×

centos apache日志怎么分割

小樊
41
2026-09-30 06:55:20
栏目: 智能运维

在 CentOS 上,Apache(httpd)日志分割常见有 三种方式,从推荐程度排序如下:


一、使用 rotatelogs(官方推荐,最常用)

Apache 自带 rotatelogs,无需额外安装。

1️⃣ 修改 Apache 配置

编辑配置文件(通常如下之一):

vim /etc/httpd/conf/httpd.conf
# 或
vim /etc/httpd/conf.d/*.conf

2️⃣ 修改日志配置

按天分割(推荐)

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

3️⃣ 重启 Apache

systemctl restart httpd

二、使用 logrotate(系统级日志管理)

适合 已经存在的日志文件。

1️⃣ 创建 logrotate 配置

vim /etc/logrotate.d/httpd

内容示例:

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

2️⃣ 测试配置

logrotate -d /etc/logrotate.d/httpd

3️⃣ 强制执行一次

logrotate -f /etc/logrotate.d/httpd

三、使用 cronolog(较少用)

需额外安装:

yum install cronolog -y

配置:

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

✅ 推荐方案总结

方式 推荐度 说明
rotatelogs ⭐⭐⭐⭐⭐ Apache 原生,实时分割
logrotate ⭐⭐⭐⭐ 系统统一管理
cronolog ⭐⭐ 已逐渐淘汰

如果你愿意,我可以:

  • 帮你写 完整 httpd.conf 示例
  • 按 每小时 / 每月 分割
  • 配合 SELinux / 权限问题 处理

告诉我你的 CentOS 版本和 Apache 版本即可。

0 踩