温馨提示×

如何定时清理centos apache日志

小樊
56
2026-09-30 07:05:22
栏目: 智能运维

在 CentOS 上定时清理 Apache 日志,常见且推荐的做法有 两种:

  1. 使用 logrotate(推荐,系统自带)
  2. 使用 crontab + 脚本手动清理

下面分别说明。


一、使用 logrotate(推荐)

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. 自定义清理策略(示例)

编辑配置:

vi /etc/logrotate.d/httpd

示例(保留 30 天,每天轮转):

/var/log/httpd/*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   # 强制执行

✅ 优点:系统级、稳定、自动压缩、无需自己写脚本


二、使用 crontab 定时清理(简单直接)

1. 编写清理脚本

vi /root/clean_apache_logs.sh

内容示例(删除 30 天前的日志):

#!/bin/bash
find /var/log/httpd -name "*.log" -mtime +30 -exec rm -f {} \;

赋予执行权限:

chmod +x /root/clean_apache_logs.sh

2. 添加定时任务

crontab -e

每天凌晨 2 点执行:

0 2 * * * /root/clean_apache_logs.sh

三、注意事项

  • ❌ 不要直接删除正在写入的 access_log / error_log
  • ✅ 使用 logrotate 或 reload httpd 才是安全方式
  • 如果是 SELinux 开启状态,脚本路径和权限需注意
  • 若使用 CentOS 7+:
    systemctl reload httpd
    

四、推荐方案总结

场景 推荐方式
服务器长期运行 logrotate ✅
临时/简单需求 crontab + find
需要压缩归档 logrotate ✅

如果你愿意,我可以:

  • 帮你写 完整 logrotate 配置
  • 或根据你的 Apache 版本 / CentOS 版本 定制方案

0 踩