option('days'); $logPath = storage_path('logs/scheduled-tasks'); if (!File::exists($logPath)) { Log::info('日志目录不存在,无需清理'); return Command::SUCCESS; } $cutoffDate = Carbon::now()->subDays($days); Log::info("开始清理 {$days} 天前的定时任务日志..."); Log::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++; Log::info("已删除: {$filename} (" . $this->formatBytes($fileSize) . ")"); } } } if ($deletedCount > 0) { Log::info("清理完成!共删除 {$deletedCount} 个日志文件,释放空间: " . $this->formatBytes($totalSize)); } else { Log::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'; } }