Showing posts with label query log. Show all posts
Showing posts with label query log. Show all posts

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.

Saturday, February 11, 2017

How to get the query executed in Laravel

As a developer you must face some situation where you have to need the sql executed. In Laravel you can see your sql query generated each step. Below is a simple code snippet to output the sql query generated by Laravel query generator. Also you have the parameters there used in Laravel query.

DB::enableQueryLog();
$total = DB::table('user')
       ->where('group_id', '=', 1)
       ->where('status', '=', 1)
       ->count();
$queries = DB::getQueryLog();
$last_query = end($queries);
echo "<pre>"; print_r($last_query); echo "</pre>";


Output following:




Array
(
    [query] => select count(*) as aggregate from `user` where `group_id` = ? and `status` = ?
    [bindings] => Array
        (
            [0] => 64
            [1] => 1
        )

    [time] => 0
)