1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Spatie\Tail; |
4
|
|
|
|
5
|
|
|
use Exception; |
6
|
|
|
use Illuminate\Console\Command; |
7
|
|
|
use Spatie\Ssh\Ssh; |
8
|
|
|
use Symfony\Component\Process\Process; |
9
|
|
|
|
10
|
|
|
class TailCommand extends Command |
11
|
|
|
{ |
12
|
|
|
protected $signature = 'tail {environment?} |
13
|
|
|
{--lines=0 : Output the last number of lines} |
14
|
|
|
{--clear : Clear the terminal screen}'; |
15
|
|
|
|
16
|
|
|
protected $description = 'Tail the latest logfile'; |
17
|
|
|
|
18
|
|
|
public function handle() |
19
|
|
|
{ |
20
|
|
|
$this->handleClearOption(); |
21
|
|
|
|
22
|
|
|
$environment = $this->argument('environment'); |
23
|
|
|
|
24
|
|
|
is_null($environment) |
25
|
|
|
? $this->tailLocally() |
26
|
|
|
: $this->tailRemotely($environment); |
27
|
|
|
} |
28
|
|
|
|
29
|
|
|
protected function handleClearOption() |
30
|
|
|
{ |
31
|
|
|
if (! $this->option('clear')) { |
32
|
|
|
return; |
33
|
|
|
} |
34
|
|
|
|
35
|
|
|
$this->output->write(sprintf("\033\143\e[3J")); |
36
|
|
|
} |
37
|
|
|
|
38
|
|
|
protected function tailLocally(): void |
39
|
|
|
{ |
40
|
|
|
$logDirectory = storage_path('logs'); |
41
|
|
|
|
42
|
|
|
Process::fromShellCommandline($this->getTailCommand(), $logDirectory) |
43
|
|
|
->setTty(true) |
44
|
|
|
->setTimeout(null) |
45
|
|
|
->run(function ($type, $line) { |
46
|
|
|
$this->handleClearOption(); |
47
|
|
|
|
48
|
|
|
$this->output->write($line); |
49
|
|
|
}); |
50
|
|
|
} |
51
|
|
|
|
52
|
|
|
protected function tailRemotely(string $environment): void |
53
|
|
|
{ |
54
|
|
|
$environmentConfig = $this->getEnvironmentConfiguration($environment); |
55
|
|
|
|
56
|
|
|
Ssh::create($environmentConfig['user'], $environmentConfig['host']) |
57
|
|
|
->configureProcess(fn (Process $process) => $process->setTty(true)) |
|
|
|
|
58
|
|
|
->onOutput(function ($type, $line) { |
59
|
|
|
$this->handleClearOption(); |
60
|
|
|
|
61
|
|
|
$this->output->write($line); |
62
|
|
|
}) |
63
|
|
|
->execute([ |
64
|
|
|
"cd {$environmentConfig['log_directory']}", |
65
|
|
|
$this->getTailCommand($environmentConfig['log_directory']), |
66
|
|
|
]); |
67
|
|
|
} |
68
|
|
|
|
69
|
|
|
protected function getEnvironmentConfiguration(string $environment): array |
70
|
|
|
{ |
71
|
|
|
$config = config('tail'); |
72
|
|
|
|
73
|
|
|
if (! isset($config[$environment])) { |
74
|
|
|
throw new Exception("No configuration set for environment `{$environment}`. Make sure this environment is specified in the `tail` config file!"); |
75
|
|
|
} |
76
|
|
|
|
77
|
|
|
return $config[$environment]; |
78
|
|
|
} |
79
|
|
|
|
80
|
|
|
public function getTailCommand(): string |
81
|
|
|
{ |
82
|
|
|
return 'tail -f -n '.$this->option('lines').' "`ls -t | head -1`"'; |
83
|
|
|
} |
84
|
|
|
} |
85
|
|
|
|