温馨提示×

centos如何轮转apache日志

小樊
44
2026-10-20 16:13:40
栏目: 智能运维

在 CentOS 上轮转(rotate)Apache 日志,常用有 两种方式:


一、使用系统自带的 logrotate(推荐)

CentOS 默认使用 logrotate 管理日志轮转,Apache 一般已经自带配置。

1. 查看 Apache 的 logrotate 配置

ls /etc/logrotate.d/
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. 手动测试轮转

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

3. 常用参数说明

  • daily / weekly / monthly:轮转周期
  • rotate N:保留 N 个旧日志
  • compress:压缩旧日志
  • size 100M:到达大小就轮转
  • postrotate ... endscript:轮转后重载 Apache

示例(按大小 + 每天):

/var/log/httpd/*log {
    daily
    size 100M
    rotate 7
    compress
    missingok
    notifempty
    sharedscripts
    postrotate
        systemctl reload httpd
    endscript
}

二、Apache 自带 rotatelogs(不依赖 logrotate)

适合在 Apache 配置中直接控制。

1. 修改 Apache 日志配置

编辑:

vi /etc/httpd/conf/httpd.conf

示例(按天轮转):

ErrorLog "|/usr/sbin/rotatelogs /var/log/httpd/error_log.%Y-%m-%d 86400"
CustomLog "|/usr/sbin/rotatelogs /var/log/httpd/access_log.%Y-%m-%d 86400" combined
  • 86400 = 一天(秒)
  • 也可按大小:5M

2. 重启 Apache

systemctl restart httpd

三、CentOS 7+ 注意事项

  • Apache 服务名:httpd
  • 日志目录:/var/log/httpd/
  • SELinux 开启时,不要手动改日志目录权限

四、推荐方案

✅ 生产环境推荐:logrotate + reload httpd
✅ 特殊需求(如精确时间):rotatelogs

如果你愿意,我可以:

  • 帮你写一份完整 logrotate 配置
  • 或按日志大小 / 天数定制方案

0 踩