0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Laravelでsqlログをファイル出力する

Posted at

はじめに

laravelはデフォルトだと、sqlのログがファイル出力されません。
開発するうえでログが残らないのは致命的なのでログがファイル出力されるようにしていきます。
今回はlaravel.logとは別ファイルを作って、sql専用のlogファイルに出力します。

環境

Laravel 12
Mysql 8.0

クエリログを有効にする

config/database.phpにある接続設定で、logging設定を追加し有効にします。

'connections' => [
    'mysql' => [
        // SQLクエリログを有効にする
        'options'   => [
            PDO::ATTR_EMULATE_PREPARES => true,
            PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
        ],
    ],
],

クエリログの保存

AppServiceProviderで全てのクエリをログに保存する設定を加えます。

use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

public function boot()
{
    // クエリ実行時にログを出力
    DB::listen(function ($query) {
        Log::info("SQL: {$query->sql}, Bindings: " . implode(', ', $query->bindings) . ", Time: {$query->time}");
    });
}

SQLログの保存ファイルの設定

config/logging.phpを以下のように設定します。

'channels' => [
    'sql' => [
        'driver' => 'single',
        'path' => storage_path('logs/sql.log'), // ログファイルを保存するパス
        'level' => 'debug',
    ],
],

これでsql.logファイルにログが出力されるようになります。

おわりに

開発環境だとdebugbarの方が便利かもしれません。
(自分は開発と本番で設定を変えたくないので、ファイルに吐いてしまいますが、、)
よい開発ライフを!

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?