option('days'); $logPath = storage_path('logs'); if (!File::isDirectory($logPath)) { $this->error("Log directory not found: {$logPath}"); return 1; } $deletedFiles = 0; $deletedSize = 0; $cutoffDate = Carbon::now()->subDays($days); $this->info("Cleaning up log files older than {$days} days (before {$cutoffDate->toDateString()})..."); $files = File::files($logPath); foreach ($files as $file) { $filename = $file->getFilename(); // Skip the current laravel.log file if ($filename === 'laravel.log') { continue; } $lastModified = Carbon::createFromTimestamp($file->getMTime()); if ($lastModified->lt($cutoffDate)) { $fileSize = $file->getSize(); try { File::delete($file->getPathname()); $deletedFiles++; $deletedSize += $fileSize; $this->line("Deleted: {$filename} (" . $this->formatBytes($fileSize) . ", modified: {$lastModified->toDateString()})"); } catch (\Exception $e) { $this->error("Failed to delete {$filename}: " . $e->getMessage()); } } } if ($deletedFiles > 0) { $this->info("\nCleanup complete!"); $this->info("Deleted {$deletedFiles} file(s), freed " . $this->formatBytes($deletedSize)); Log::channel('cleanup')->info("Log cleanup completed", [ 'deleted_files' => $deletedFiles, 'freed_space' => $this->formatBytes($deletedSize), 'days' => $days ]); } else { $this->info("No old log files found to delete."); } return 0; } /** * Format bytes to human readable format * * @param int $bytes * @return string */ private function formatBytes($bytes) { $units = ['B', 'KB', 'MB', 'GB']; $bytes = max($bytes, 0); $pow = floor(($bytes ? log($bytes) : 0) / log(1024)); $pow = min($pow, count($units) - 1); $bytes /= (1 << (10 * $pow)); return round($bytes, 2) . ' ' . $units[$pow]; } }