Laravel は PHP のフレームワークでコンソール上のコマンドを簡易に作成するための仕組みも備えています。コンソールコマンドを作る仕組みは Artisan といい、Laravel 組み込みのコマンドもこの Artisan でつくられています。
Artisanコンソール 6.x Laravel
Artisan は便利なのですが、次の様にコンソールによってはエラー表示が非常に見づらくなります。
新たに自分でコマンドを作る際には以前紹介したように error メソッドを上書きすれば良いのですが、既存のコマンドはこの方法ではどうにもなりません。この記事ではこれを解決します。
【Laravel】Artisanコマンドのコンソール表示を見やすくする – 株式会社シーポイントラボ | 浜松のシステム・RTK-GNSS開発
解決のために Laravel が用意したプロジェクトルートにある artisan というファイルを変更します。これは拡張子なしのファイルですが、中身は PHP のコードそのものです。これを次の様に書き換えます。
クリックでソースコードを展開
#!/usr/bin/env php
<?php
define('LARAVEL_START', microtime(true));
/*
|--------------------------------------------------------------------------
| Register The Auto Loader
|--------------------------------------------------------------------------
|
| Composer provides a convenient, automatically generated class loader
| for our application. We just need to utilize it! We'll require it
| into the script here so that we do not have to worry about the
| loading of any our classes "manually". Feels great to relax.
|
*/
require __DIR__.'/vendor/autoload.php';
$app = require_once __DIR__.'/bootstrap/app.php';
/*
|--------------------------------------------------------------------------
| Run The Artisan Application
|--------------------------------------------------------------------------
|
| When we run the console application, the current CLI command will be
| executed in this console and the response sent back to a terminal
| or another output device for the developers. Here goes nothing!
|
*/
$kernel = $app->make(Illuminate\Contracts\Console\Kernel::class);
/** ここから変更開始 */
$output = new Symfony\Component\Console\Output\ConsoleOutput;
$output->getFormatter()// コンソールアウトプットクラスから文字列のフォーマッターインスタンスを取得
->setStyle(// フォーマッターにエラー時は 赤文字、黒地、太文字 とセット
'error',
new Symfony\Component\Console\Formatter\OutputFormatterStyle('red', 'black',[
'bold'
])
);
// Laravel のコンソールのカーネルにスタイルを変えたコンソールアウトプットインスタンスを渡す
$status = $kernel->handle(
$input = new Symfony\Component\Console\Input\ArgvInput,
$output
);
/** 変更ここまで */
/*
|--------------------------------------------------------------------------
| Shutdown The Application
|--------------------------------------------------------------------------
|
| Once Artisan has finished running, we will fire off the shutdown events
| so that any final work may be done by the application before we shut
| down the process. This is the last thing to happen to the request.
|
*/
$kernel->terminate($input, $status);
exit($status);
Symfony で用意されたコンソール出力クラスにエラーの場合ではこの色で表記する、と記述します。これで次画像の様に見やすくなります。
ここでは黒地に太い赤文字としましたが、他の色も当然使えます。これは Symfony の Console コンポーネントの出力に関するドキュメントが詳しいです。
How to Color and Style the Console Output (Symfony Docs)

