24
25

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 5 years have passed since last update.

LaravelでSQL文をlaravel.logに出力する

Last updated at Posted at 2018-02-14

Railsみたいにhttpリクエスト後に発行されるSQLをログファイルに出力する

環境

  • Laravel: 5.6.3

コード

app/Providers/AppServiceProvider.php
    public function register()
    {
        // SQL Log
        \DB::listen(function ($query) {
            $sql = $query->sql;
            for ($i = 0; $i < count($query->bindings); $i++) {
                $sql = preg_replace("/\?/", $query->bindings[$i], $sql, 1);
            }

            \Log::debug("SQL", ["time" => sprintf("%.2f ms", $query->time), "sql" => $sql]);                                                                
        });
    }
[2018-02-14 09:17:04] laravel.DEBUG: SQL {"time":"24.56 ms","sql":"select * from \"groups\" order by createdday desc limit 10"}
[2018-02-14 09:17:04] laravel.DEBUG: SQL {"time":"4.98 ms","sql":"select count(*) as aggregate from \"groups\""

参考

24
25
1

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
24
25

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?