Thursday, July 6, 2017

Laravel 5: Logging All DB Query | Log Queries | Listen Query Events | Query Logging | Sql Logging | Log SQL | DB Connection Class | Laravel Database Connection | Laravel DB Connection Query Run Method

Laravel 5: Logging All DB Query | Log Queries | Listen Query Events | Query Logging | Sql Logging | Log SQL | DB Connection Class | Laravel Database Connection | Laravel DB Connection Query Run Method.

Logging query in Laravel is easy. You can then register event listener for DB. At first you need to create an service provider in directory ("project/app/Providers" ) named QueryLogProvider with following contents:


<?php
namespace App\Providers;

use Monolog\Logger;
use Illuminate\Support\Facades\DB;
use Monolog\Handler\StreamHandler;
use Illuminate\Support\ServiceProvider;

class QueryLogProvider extends ServiceProvider
{
    public function register()
    {
        DB::listen(function ($query) {
            $logFile = storage_path('logs/query-log-'.date("Y-m-d").'.log');
            $stream = new Logger('log');
            $stream->pushHandler(new StreamHandler($logFile));
            $bindings = $query->bindings;
            $time = $query->time;
            $stream->info($query->sql, compact('bindings', 'time'));
        });
    }
}

You are done with creating provider. Now you have to register in file "project/config/app.php" in section 


'providers' => [
    .....,
    App\Providers\QueryLogProvider::class
],

All your queries will be stored on the location "project/storage/logs" with prefix file name "query-log".

But you can do some wired things, editing source code. To do so first need to open your connection class:

Illuminate\Database\Connection

and navigate to function:

protected function run($query, $bindings, Closure $callback)

actually all query in Laravel passed through this method.

So you can do whatever you wish to do here.

2 comments: