QueryExceptionの内容のみ特定のログファイルに記録

目的

SQL関連のエラーだけ特定のログファイルに記録されるようにしたい。

手順

  1. config/logging.php の編集
  2. app/Exceptions/Handler.php の編集
  3. 動作確認

config/logging.php

singleチャンネルの下にでも追加する。

'sql_error' => [
            'driver' => 'daily',
            'path' => storage_path('logs/QueryException/sql_error.log'),
            'level' => 'error',
            'days' => 365,
            'replace_placeholders' => true,
        ],

replace_placeholdersについては、次のページが参考になる。

[10.x] Add replace_placeholders to log channels by alanpoulain · Pull Request #6139 · laravel/laravel
Following laravel/framework#46344. Add replace_placeholders to true to log channels and PsrLogMessageProcessor for monol...

app/Exceptions/Handler.php

下記のように追加する。

public function register(): void
    {
        $this->reportable(function (Throwable $e) {
            //
        });

        $this->reportable(function (QueryException $e) {
            Log::channel('sql_error')->error($e->getMessage());
            Log::channel('sql_error')->error($e->getSql());
            Log::channel('sql_error')->error($e->getBindings());
        });
    }

動作確認

何らかのコントローラで、次のエラーが出るコードを実行し、
storage/logsフォルダに作成される「sql_error-YYYY-MM-DD.log」というファイルを確認すれば良い。

DB::table('aiueo')->get();

コメント

タイトルとURLをコピーしました