目的
Laravel Commandの開始時と終了時に実行コマンドのログを自動で出力するようにしたい。
パラメータ指定がある場合は合わせて出力させたい。
バージョン
Laravel 5.7
実装
Laravel EventListnerを使って実装を行います。
イベント/リスナ登録
EventServiceProvider
の$listen
に以下のようにイベントとリスナを登録します。
Commandの開始と終了のイベントは既に定義されているので、それに対応するリスナを自分で定義します。
<?php
namespace App\Providers;
class EventServiceProvider extends ServiceProvider
{
protected $listen = [
CommandStarting::class => [
CommandStartLogger::class
],
CommandFinished::class => [
CommandFinishLogger::class
]
];
}
リスナ生成
以下のコマンドで上で定義したリスナを生成します。
$ php artisan event:generate
リスナ実装
共通処理用親クラス
コマンドのパラメータを取得するのにひと手間が必要なので、共通処理用のクラスApp\Listeners\CommandLogger
を実装します。
また、Commandを定期実行するためのコマンドschedule:run
は不要なので出力しないようにします。
<?php
namespace App\Listeners;
abstract class CommandLogger
{
protected function shouldLog($command)
{
$ignoredCommands = [
'schedule:run'
];
return !in_array($command, $ignoredCommands);
}
protected function getCommandDetail($event)
{
$input = (array) $event->input;
$index = '' . "\0" . 'Symfony\\Component\\Console\\Input\\ArgvInput' . "\0" . 'tokens';
$command = implode(' ', $input[$index]);
return $command;
}
}
コマンド開始リスナ
コマンド開始ログを出力するためのリスナを実装します。
<?php
namespace App\Listeners;
use Log;
class CommandStartLogger extends CommandLogger
{
public function handle($event)
{
if ($this->shouldLog($event->command)) {
Log::info('Start Command ' . $this->getCommandDetail($event));
}
}
}
コマンド終了リスナ
コマンド終了ログを出力するためのリスナを実装します。
必要に応じてメモリ使用率などを出力してもいいと思います。
<?php
namespace App\Listeners;
use Log;
class CommandFinishLogger extends CommandLogger
{
public function handle($event)
{
if ($this->shouldLog($event->command)) {
Log::info('Finish Command ' . $this->getCommandDetail($event));
}
}
}
試してみる
テスト用コマンド実装
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
class TestCommand extends Command
{
protected $signature = 'command:test {--param=}';
public function handle()
{
Log::info('This is test command.');
}
}
コマンド実行
$ php artisan command:test --param=hogehoge
ログ確認
[2020-03-04 01:03:47] local.INFO: Start Command command:test --param=hogehoge
[2020-03-04 01:03:47] local.INFO: This is test command.
[2020-03-04 01:03:47] local.INFO: Finish Command command:test --param=hogehoge