Files
toolbox/app/Console/Commands/CleanScheduledTaskLogsCommand.php

73 lines
2.3 KiB
PHP

<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\File;
use Carbon\Carbon;
class CleanScheduledTaskLogsCommand extends Command
{
protected $signature = 'logs:clean-scheduled-tasks {--days=7 : 保留最近几天的日志}';
protected $description = '清理定时任务日志文件,删除指定天数之前的日志';
public function handle(): int
{
$days = (int) $this->option('days');
$logPath = storage_path('logs/scheduled-tasks');
if (!File::exists($logPath)) {
$this->info('日志目录不存在,无需清理');
return Command::SUCCESS;
}
$cutoffDate = Carbon::now()->subDays($days);
$this->info("开始清理 {$days} 天前的定时任务日志...");
$this->info("截止日期: {$cutoffDate->format('Y-m-d')}");
$files = File::files($logPath);
$deletedCount = 0;
$totalSize = 0;
foreach ($files as $file) {
$filename = $file->getFilename();
// 匹配日志文件名格式: task-name-YYYY-MM-DD.log
if (preg_match('/-(\d{4}-\d{2}-\d{2})\.log$/', $filename, $matches)) {
$fileDate = Carbon::parse($matches[1]);
if ($fileDate->lt($cutoffDate)) {
$fileSize = $file->getSize();
$totalSize += $fileSize;
File::delete($file->getPathname());
$deletedCount++;
$this->line("已删除: {$filename} (" . $this->formatBytes($fileSize) . ")");
}
}
}
if ($deletedCount > 0) {
$this->info("清理完成!共删除 {$deletedCount} 个日志文件,释放空间: " . $this->formatBytes($totalSize));
} else {
$this->info('没有需要清理的日志文件');
}
return Command::SUCCESS;
}
private function formatBytes(int $bytes): string
{
if ($bytes >= 1073741824) {
return number_format($bytes / 1073741824, 2) . ' GB';
} elseif ($bytes >= 1048576) {
return number_format($bytes / 1048576, 2) . ' MB';
} elseif ($bytes >= 1024) {
return number_format($bytes / 1024, 2) . ' KB';
}
return $bytes . ' B';
}
}