2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

LaravelのSQLを開発環境時のみログ出力する

Last updated at Posted at 2021-01-30

はじめに

開発用ライブラリの『Laravel Debugbar』では、
APIやバッチ処理実行時のSQLが確認できないため、
開発時のみ発行しているSQLをログファイルに出力するようにする。

環境

PHP 7.4.9
Laravel Framework 8.25.0

SQLログ出力設定

app\Providers\AppServiceProvider.php
    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        //
        // 開発環境以外の場合、SQLログを出力
        if (!app()->isProduction()) {
            $this->dataBaseQuery();
        }
    }

    private function dataBaseQuery()
    {
        \DB::listen(function ($query): void {
            $sql = $query->sql;
    
            foreach ($query->bindings as $binding) {
                if (is_string($binding)) {
                    $binding = "'{$binding}'";
                } elseif (is_bool($binding)) {
                    $binding = $binding ? '1' : '0';
                } elseif (is_int($binding)) {
                    $binding = (string) $binding;
                } elseif ($binding === null) {
                    $binding = 'NULL';
                } elseif ($binding instanceof Carbon) {
                    $binding = "'{$binding->toDateTimeString()}'";
                } elseif ($binding instanceof DateTime) {
                    $binding = "'{$binding->format('Y-m-d H:i:s')}'";
                }
    
                $sql = preg_replace('/\\?/', $binding, $sql, 1);
            }
    
            // SQL・queryTimeログ出力
            // \Log::debug('SQL', ['sql' => $sql, 'time' => "{$query->time} ms"]);
            // SQLログ出力
            \Log::debug($sql);
        });
    
        \Event::listen(TransactionBeginning::class, function (TransactionBeginning $event): void {
            \Log::debug('START TRANSACTION');
        });
    
        \Event::listen(TransactionCommitted::class, function (TransactionCommitted $event): void {
            \Log::debug('COMMIT');
        });
    
        \Event::listen(TransactionRolledBack::class, function (TransactionRolledBack $event): void {
            \Log::debug('ROLLBACK');
        });
    }
storage\logs\laravel.log
[2021-01-30 23:02:43] local.DEBUG: SELECT * FROM users
.env
APP_ENV=local

本番環境は『APP_ENV=production』に変更するとSQLは出力されません。

参考記事

Laravel SQLの実行クエリログを出力する
https://qiita.com/ucan-lab/items/753cb9d3e4ceeb245341

2
1
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
2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?