Kaspars's avatar

Database log

Hello! How would one go about logging database queries?

0 likes
5 replies
pixelpeter's avatar
Level 19

One global approach could be

        \DB::listen(function($sql, $bindings, $time) {
            \Log::info($sql, $bindings, $time);
        });
Kaspars's avatar

That would be the obvious thing, which I tried. But it doesnt seem to work.

pixelpeter's avatar

You have to enable facades and eloquent in bootstrap/app.php

...
$app->withFacades();

$app->withEloquent();
...

Then this code in routes.php is working fine for me

\DB::listen(function($sql, $bindings, $time) {
    
    var_dump($sql, $bindings, $time);

    \Log::info($sql);
    \Log::info(print_r($bindings,1));
    \Log::info($time);
});

$app->get('/test', function() use ($app) {

  \App\Test::all();

});

Given me this entries in lumen.log

[2015-06-21 12:55:13] lumen.INFO: select * from `tests`  
[2015-06-21 12:55:13] lumen.INFO: Array
(
)
  
[2015-06-21 12:55:13] lumen.INFO: 0.26  
Kaspars's avatar

Tracked it down. When calling the query I was resolving the DB object from Service Container, and it wasnt calling the event for some reason.

app()->make("db")->table("table")->get(); //event not called
\DB::table("table")->get(); //event called

Please or to participate in this conversation.