Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
88.00% covered (warning)
88.00%
44 / 50
66.67% covered (warning)
66.67%
2 / 3
CRAP
0.00% covered (danger)
0.00%
0 / 1
PruneLogs
88.00% covered (warning)
88.00%
44 / 50
66.67% covered (warning)
66.67%
2 / 3
16.44
0.00% covered (danger)
0.00%
0 / 1
 handle
85.71% covered (warning)
85.71%
36 / 42
0.00% covered (danger)
0.00%
0 / 1
12.42
 relative
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 human
100.00% covered (success)
100.00%
7 / 7
100.00% covered (success)
100.00%
1 / 1
3
1<?php
2
3namespace App\Console\Commands;
4
5use Illuminate\Console\Command;
6use Illuminate\Support\Facades\Log;
7use RecursiveDirectoryIterator;
8use RecursiveIteratorIterator;
9use SplFileInfo;
10
11/**
12 * Deletes log files under storage/logs that nothing else cleans up.
13 *
14 * The `daily` channels prune their own files, but several kinds never get
15 * deleted: logs/cofrai/YYYY_MM_DD.log from the old frozen-date `single`
16 * channel, the per-run cofrai-bulk-spawn-*.log shell redirects, and
17 * leftovers from channels that were `single` before FIRE-1449. On
18 * 2026-09-28 a full disk took Redis (MISCONF), MySQL tmp tables, logging
19 * and logins down with it.
20 *
21 * Only files whose last write is older than --days are removed, so a file
22 * that is still being written is never touched.
23 */
24class PruneLogs extends Command
25{
26    protected $signature = 'logs:prune
27        {--days= : Delete log files not written for this many days (default: LOG_DAILY_DAYS, 14)}
28        {--dry-run : List what would be deleted, delete nothing}';
29
30    protected $description = 'Delete log files in storage/logs not written to for N days';
31
32    public function handle(): int
33    {
34        $days = (int) ($this->option('days') ?? config('logging.channels.daily.days', 14));
35
36        if ($days < 1) {
37            $this->error('--days must be at least 1.');
38
39            return Command::FAILURE;
40        }
41
42        $dir = storage_path('logs');
43        $cutoff = time() - $days * 86400;
44        $dryRun = (bool) $this->option('dry-run');
45
46        $deleted = 0;
47        $bytes = 0;
48        $failed = [];
49
50        $files = new RecursiveIteratorIterator(
51            new RecursiveDirectoryIterator($dir, RecursiveDirectoryIterator::SKIP_DOTS)
52        );
53
54        /** @var SplFileInfo $file */
55        foreach ($files as $file) {
56            if (! $file->isFile() || ! preg_match('/\.log(\.\d+)?(\.gz)?$/', $file->getFilename())) {
57                continue;
58            }
59
60            if ($file->getMTime() >= $cutoff) {
61                continue;
62            }
63
64            $size = $file->getSize();
65
66            if ($dryRun) {
67                $this->line('would delete '.$this->relative($file, $dir).' ('.$this->human($size).')');
68            } elseif (! @unlink($file->getPathname())) {
69                $failed[] = $this->relative($file, $dir);
70
71                continue;
72            }
73
74            $deleted++;
75            $bytes += $size;
76        }
77
78        $summary = sprintf(
79            '%s %d log file(s) older than %d days, %s.',
80            $dryRun ? 'Would delete' : 'Deleted',
81            $deleted,
82            $days,
83            $this->human($bytes),
84        );
85        $this->info($summary);
86
87        // One line per run, not per file (FIRE-1449 log-volume convention).
88        if (! $dryRun && $deleted > 0) {
89            Log::info('logs:prune '.$summary);
90        }
91
92        if ($failed !== []) {
93            // Usually a file owned by another user (root, cron) in a
94            // directory this user can't write — the same ownership split
95            // behind the "could not be opened in append mode" errors.
96            $this->warn('Could not delete '.count($failed).' file(s): '.implode(', ', array_slice($failed, 0, 20)));
97            Log::warning('logs:prune could not delete '.count($failed).' file(s), check storage/logs ownership', [
98                'files' => array_slice($failed, 0, 20),
99            ]);
100        }
101
102        return Command::SUCCESS;
103    }
104
105    private function relative(SplFileInfo $file, string $dir): string
106    {
107        return ltrim(str_replace('\\', '/', substr($file->getPathname(), strlen($dir))), '/');
108    }
109
110    private function human(int $bytes): string
111    {
112        $units = ['B', 'KB', 'MB', 'GB'];
113        $i = 0;
114        $value = (float) $bytes;
115
116        while ($value >= 1024 && $i < count($units) - 1) {
117            $value /= 1024;
118            $i++;
119        }
120
121        return round($value, 1).' '.$units[$i];
122    }
123}