Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

My team and I are working on a rather big project. There's queries going on everywhere - in controllers, in view composers in views (lazy loading) and probably in some other services as well. It's getting hard to keep a track of it all and the page load speed is fairly slow at the moment.

Where would I put \DB::enableQueryLog() and \DB::getQueryLog() to log ALL the queries and dump them? Basically I'm looking for some place in code that happens before any of the queries happen (to put enableQueryLog()) and I'm looking for a place that happens after the views render (to dump getQueryLog()).

What would be a good way to go about this?

Thanks in advance.

like image 907
DevK Avatar asked Dec 15 '16 11:12

DevK


People also ask

How do I log all SQL queries in laravel?

Log in the default log file “laravel. log” located at “storage/logs”. To log SQL queries, we have to add the following code snippet in the “AppServiceProvider. php” file in the “boot()” function, located at “app/Providers”.

How do I enable query logging in laravel?

Enable query log LaravelUse the enableQueryLog method: Use the enableQueryLog method: DB::connection()->enableQueryLog(); You can get an array of the executed queries by using the getQueryLog method: $queries = DB::getQueryLog();

How do I get laravel logs?

By default, Laravel is configured to create a single log file for your application, and this file is stored in app/storage/logs/laravel. log .


1 Answers

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     ]); }); 
like image 164
Hudson Pereira Avatar answered Sep 24 '22 22:09

Hudson Pereira