温馨提示×

centos如何切割apache日志

小樊
44
2026-09-21 09:59:48
栏目: 智能运维

在 CentOS 上切割 Apache 日志,常见做法有 三种:
1️⃣ 使用 Apache 自带的 rotatelogs
2️⃣ 使用系统自带的 logrotate(最推荐)
3️⃣ 自己写脚本 + cron(不推荐,除非特殊需求)

下面按顺序说明。


一、使用 logrotate(CentOS 默认推荐方式)

CentOS 通常已经安装了 logrotate,并且 Apache 的日志切割也是用它管理的。

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. 常见参数说明

  • daily / weekly / monthly:切割周期
  • rotate 30:保留 30 个旧日志
  • compress:压缩旧日志
  • missingok:日志不存在也不报错
  • notifempty:空日志不切割

3. 修改为例:每天切割并保留 30 天

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

4. 手动测试

logrotate -d /etc/logrotate.d/httpd   # 模拟执行
logrotate -f /etc/logrotate.d/httpd   # 强制执行

✅ 优点:系统级、稳定、CentOS 官方推荐


二、使用 Apache 的 rotatelogs(按大小或时间切割)

适合需要 按小时/天/大小 切割,且不依赖 logrotate。

1. 修改 Apache 配置

编辑:

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

✅ 优点:实时切割
❌ 缺点:不会自动压缩,日志多了要自己清理


三、使用 cron + 脚本(不推荐)

示例(每天凌晨切割):

0 0 * * * mv /var/log/httpd/access_log /var/log/httpd/access_log.$(date +%F)
systemctl reload httpd

⚠️ 容易丢日志,不建议生产环境使用。


四、推荐方案总结

场景 推荐方式
CentOS 服务器 ✅ logrotate
需要精确时间切割 rotatelogs
简单测试 cron

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

  • Apache 版本(httpd -v)
  • 日志路径
  • 想按 天 / 大小 / 访问量 切割

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

0 踩