在CentOS系統上清理PHP日志文件可以通過以下幾種方法進行:
定位日志文件:
find
命令查找日志文件。例如,查找 /var/log
目錄下所有日志文件:find /var/log -name "*.log"
截斷日志文件:
truncate
命令清空日志文件內容,但保留文件本身。例如,截斷所有大小超過 50MB 且修改時間超過 7 天的日志文件:find /var/log -type f -name "*.log" -size +50M -mtime +7 -exec truncate -s 0 {} \;
刪除舊的日志文件:
rm
命令刪除不再需要的舊日志文件。例如,刪除修改時間超過 30 天的日志文件:find /var/log -type f -name "*.log" -mtime +30 -exec rm -f {} \;
logrotate
logrotate
:
logrotate
會定期輪轉日志文件,將舊的日志文件壓縮或刪除,并創建新的日志文件。配置文件位于 /etc/logrotate.conf
,可以在這里設置日志輪轉的策略。例如:/var/log/messages {
rotate 5
weekly
compress
delaycompress
missingok
notifempty
create 0640 root utmp
postrotate
/usr/bin/killall -HUP syslogd
endscript
}
/var/log/messages
文件將每周輪轉一次,保留 5 個舊的壓縮日志文件。創建清理腳本:
log_cleanup.sh
腳本:#!/bin/bash
find /var/log -type f -name "*.log" -mtime +30 -exec rm -f {} \;
chmod +x log_cleanup.sh
設置 cron 作業:
0 3 * * * /path/to/log_cleanup.sh
刪除臨時文件和日志:
<?php
$temp_folder = '/path/to/temp_folder';
$log_file = '/path/to/log_file';
// 刪除臨時文件夾
if (is_dir($temp_folder)) {
$files = glob($temp_folder . '/*');
foreach ($files as $file) {
if (is_file($file)) {
unlink($file);
}
}
rmdir($temp_folder);
}
// 清空日志文件
if (file_exists($log_file)) {
file_put_contents($log_file, '');
}
?>
定期清理:
cron
任務或計劃任務來定期執行上述清理操作,以確保系統的正常運行。通過以上方法,可以有效地管理和清理 CentOS 系統上的 PHP 日志文件,釋放磁盤空間,提升系統性能。