|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace Spatie\Tail; |
|
4
|
|
|
|
|
5
|
|
|
use SplFileInfo; |
|
6
|
|
|
use Illuminate\Console\Command; |
|
7
|
|
|
use Illuminate\Support\Facades\File; |
|
8
|
|
|
use Symfony\Component\Process\Process; |
|
9
|
|
|
|
|
10
|
|
|
class TailCommand extends Command |
|
11
|
|
|
{ |
|
12
|
|
|
protected $signature = 'tail |
|
13
|
|
|
{--lines=0 : Output the last number of lines} |
|
14
|
|
|
{--H|hide-stack-traces : Filter out the stack traces} |
|
15
|
|
|
{--clear : Clear the terminal screen}'; |
|
16
|
|
|
|
|
17
|
|
|
protected $description = 'Tail the latest logfile'; |
|
18
|
|
|
|
|
19
|
|
|
public function handle() |
|
20
|
|
|
{ |
|
21
|
|
|
$logDirectory = storage_path('logs'); |
|
22
|
|
|
|
|
23
|
|
|
if (! $path = $this->findLatestLogFile($logDirectory)) { |
|
24
|
|
|
$this->warn("Could not find a log file in `{$logDirectory}`."); |
|
25
|
|
|
|
|
26
|
|
|
return; |
|
27
|
|
|
} |
|
28
|
|
|
|
|
29
|
|
|
$lines = $this->option('lines'); |
|
30
|
|
|
|
|
31
|
|
|
$filters = $this->getFilters(); |
|
32
|
|
|
|
|
33
|
|
|
$tailCommand = "tail -n {$lines} -f ".escapeshellarg($path)." {$filters}"; |
|
34
|
|
|
|
|
35
|
|
|
$this->handleClearOption(); |
|
36
|
|
|
|
|
37
|
|
|
(new Process($tailCommand)) |
|
38
|
|
|
->setTty(true) |
|
39
|
|
|
->setTimeout(null) |
|
40
|
|
|
->run(function ($type, $line) { |
|
41
|
|
|
$this->handleClearOption(); |
|
42
|
|
|
|
|
43
|
|
|
$this->output->write($line); |
|
44
|
|
|
}); |
|
45
|
|
|
} |
|
46
|
|
|
|
|
47
|
|
|
protected function findLatestLogFile(string $directory) |
|
48
|
|
|
{ |
|
49
|
|
|
$logFile = collect(File::allFiles($directory)) |
|
50
|
|
|
->sortByDesc(function (SplFileInfo $file) { |
|
51
|
|
|
return $file->getMTime(); |
|
52
|
|
|
}) |
|
53
|
|
|
->first(); |
|
54
|
|
|
|
|
55
|
|
|
return $logFile |
|
56
|
|
|
? $logFile->getPathname() |
|
57
|
|
|
: false; |
|
58
|
|
|
} |
|
59
|
|
|
|
|
60
|
|
|
protected function handleClearOption() |
|
61
|
|
|
{ |
|
62
|
|
|
if (! $this->option('clear')) { |
|
63
|
|
|
return; |
|
64
|
|
|
} |
|
65
|
|
|
|
|
66
|
|
|
$this->output->write(sprintf("\033\143\e[3J")); |
|
67
|
|
|
} |
|
68
|
|
|
|
|
69
|
|
|
protected function getFilters() |
|
70
|
|
|
{ |
|
71
|
|
|
if ($this->option('hide-stack-traces')) { |
|
72
|
|
|
return '| grep -i -E "^\[\d{4}\-\d{2}\-\d{2} \d{2}:\d{2}:\d{2}\]|Next [\w\W]+?\:"'; |
|
73
|
|
|
} |
|
74
|
|
|
} |
|
75
|
|
|
} |
|
76
|
|
|
|