Laravel 5.3 - How to log all queries on a page?

前提是你 提交于 2019-11-30 01:54:29
Hudson Pereira

Here comes the perfect example:

https://laravel.com/docs/5.3/database#listening-for-query-events

Open app\Providers\AppServiceProvider.php and add the following to Boot() function:

DB::listen(function ($query) {
    var_dump([
        $query->sql,
        $query->bindings,
        $query->time
    ]);
});

You can add this to the Providers/AppServiceProvider.php file and check them in the laravel log file with tail:

tail -f storage/logs/laravel.log

You can even filter with queries you want to log. For example, here I was using Laravel Passport, and didn't want to log all the oauth queries.

use Illuminate\Support\Facades\App;
use Illuminate\Support\Facades\Event;
use Illuminate\Support\Facades\Log;

public function register() {
    if (App::environment('local') && env('APP_URL') == 'http://localhost') {
        Event::listen('Illuminate\Database\Events\QueryExecuted', function ($query) {
            // filter oauth ones
            if (!str_contains($query->sql, 'oauth')) {
                Log::debug($query->sql . ' - ' . serialize($query->bindings));
            }
        });
    }
}
Umang Soni

If you want to print a query which is executed on your app do following steps.

Step1: Go to your AppServiceProvider.php file. // File path App\Providers\AppServiceProvider.php

Step2: Make boot() method and paste below code.

public function boot() {
        // Log queries
        if (true) {
            \DB::listen(function ($query) {
                \Log::info(
                    $query->sql, $query->bindings, $query->time
                );
            });
        }
    }

Step3: Now you can see you queries in lumen.log or laravel.log file. File path is laravel_app\storage\logs\laravel.log or lumen.log.

Enjoy....

Elco

Put this code right above the code where your query is executed

\DB::listen(function($sql) {
  die(\Illuminate\Support\Str::replaceArray('?', $sql->bindings, $sql->sql));
});

Just modified for executable query:

\DB::listen(function ($query) {
   // Enclose in single quotes for string params.
   $bindings = collect($query->bindings)->map(function ($param) {
      if(is_numeric($param)) {
        return $param;
      } else {
        return "'$param'";
      }
   });

   \Log::info(\Illuminate\Support\Str::replaceArray('?', $bindings->toArray(), $query->sql));
});

add a middleware that executes after the request is done and logs your queries ... see Terminable Middlwares

Mick

Are you using MySQL? You can just tail the log.

How to show the last queries executed on MySQL?

Or use the Laravel Debug Bar?

Additioanlly There's package available also:

log-my-queries

https://packagist.org/packages/technoknol/log-my-queries

Just install and add it's entry to middleware. It will log all the queries in laravel.log default log file.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!