|
| 1 | +<?php |
| 2 | + |
| 3 | +namespace Devdot\LogArtisan\Commands; |
| 4 | + |
| 5 | +use Devdot\LogArtisan\Models\DriverMultiple; |
| 6 | +use Illuminate\Console\Command; |
| 7 | +use Illuminate\Support\Facades\Log; |
| 8 | + |
| 9 | +class ClearLog extends Command |
| 10 | +{ |
| 11 | + /** |
| 12 | + * The name and signature of the console command. |
| 13 | + * |
| 14 | + * @var string |
| 15 | + */ |
| 16 | + protected $signature = 'log:clear |
| 17 | + {channel? : Channel that should be cleared} |
| 18 | + {--all : Clear all channels that are configured} |
| 19 | + '; |
| 20 | + |
| 21 | + /** |
| 22 | + * The console command description. |
| 23 | + * |
| 24 | + * @var string |
| 25 | + */ |
| 26 | + protected $description = 'Clear log files'; |
| 27 | + |
| 28 | + /** |
| 29 | + * Execute the console command. |
| 30 | + * |
| 31 | + * @return int |
| 32 | + */ |
| 33 | + public function handle() |
| 34 | + { |
| 35 | + // make sure the all flag is set when no channel is provided |
| 36 | + if(empty($this->argument('channel')) && $this->option('all') === false) { |
| 37 | + $this->error('No channel name provided. If you wish to clear all logs, set the --all option explicitly.'); |
| 38 | + return Command::INVALID; |
| 39 | + } |
| 40 | + |
| 41 | + // now create the channel driver objects safely |
| 42 | + $channels = []; |
| 43 | + if($this->argument('channel')) { |
| 44 | + $channels[] = $this->argument('channel'); |
| 45 | + // check if this channel is configured |
| 46 | + if(empty(config('logging.channels.'.$channels[0]))) { |
| 47 | + $this->error('Channel is not configured!'); |
| 48 | + return Command::INVALID; |
| 49 | + } |
| 50 | + } |
| 51 | + if($this->option('all')) { |
| 52 | + $channels = [ |
| 53 | + config('logging.default'), |
| 54 | + config('logging.deprecations.channel'), |
| 55 | + 'emergency', |
| 56 | + ]; |
| 57 | + } |
| 58 | + |
| 59 | + // make sure we have no empty channels |
| 60 | + $channels = array_filter($channels, fn($channel) => $channel !== null); |
| 61 | + |
| 62 | + // create a multi driver for our channel selection |
| 63 | + $multidriver = new DriverMultiple('', $channels); |
| 64 | + |
| 65 | + // and load the files through the driver |
| 66 | + $files = $multidriver->getFilenames(); |
| 67 | + |
| 68 | + $this->line('Found '.count($files).' log files'); |
| 69 | + |
| 70 | + // loop through the files and clear them |
| 71 | + foreach($files as $file) { |
| 72 | + $this->line($file); |
| 73 | + // clear the file |
| 74 | + if(unlink($file) == false) { |
| 75 | + $this->error('Failed unlinking file!'); |
| 76 | + continue; |
| 77 | + } |
| 78 | + // manually write into log |
| 79 | + Log::build([ |
| 80 | + 'driver' => 'single', |
| 81 | + 'path' => $file, |
| 82 | + ])->info('Log cleared through Artisan console!'); |
| 83 | + } |
| 84 | + |
| 85 | + return Command::SUCCESS; |
| 86 | + } |
| 87 | +} |
0 commit comments