温馨提示×

centos如何清理apache日志

小樊
45
2026-10-09 01:03:59
栏目: 智能运维

在 CentOS 上清理 Apache 日志,常见做法有手动清理、日志轮转(推荐)和自动定时清理。下面分别说明。


一、Apache 日志位置(常见)

/var/log/httpd/access_log
/var/log/httpd/error_log

(如果你用的是 yum 安装的 Apache,一般就在这个目录)


二、手动清理(不推荐长期使用)

1. 清空日志文件(保留文件)

sudo truncate -s 0 /var/log/httpd/access_log
sudo truncate -s 0 /var/log/httpd/error_log

或

sudo > /var/log/httpd/access_log
sudo > /var/log/httpd/error_log

⚠️ 不建议直接 rm,否则 Apache 可能仍占用旧文件,导致磁盘不释放。

2. 删除旧日志(已轮转的)

sudo rm -f /var/log/httpd/access_log-*
sudo rm -f /var/log/httpd/error_log-*

三、使用 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>&1 || true
    endscript
}

2. 手动执行一次轮转

sudo logrotate -f /etc/logrotate.d/httpd

3. 测试而不执行

sudo logrotate -d /etc/logrotate.d/httpd

四、设置自动清理策略(示例)

编辑:

sudo 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
}

说明:

  • daily:每天轮转
  • rotate 30:保留 30 份
  • compress:压缩旧日志

五、查看磁盘占用

df -h
du -sh /var/log/httpd

六、注意事项

  • ✅ 清理后建议重载 Apache:
    sudo systemctl reload httpd
    
  • ❌ 不要直接 rm 正在写入的日志
  • 如果使用 journalctl,也可查看:
    sudo journalctl -u httpd
    

如果你愿意,我可以帮你写一份适合你服务器的 logrotate 配置或定时清理脚本。

0 踩