#database #development #laravel #logging #php #sql
First, add a logging channel in config/logging.php
:
1return [
2 'channels' => [
3 'queries' => [
4 'driver' => 'daily',
5 'path' => storage_path('logs/queries.log'),
6 'level' => 'debug',
7 'days' => 28,
8 ],
9 ],
10];
After that, update your AppServiceProvider
in app/Providers/AppServiceProvider.php
:
1use Illuminate\Support\Facades\DB;
2use Illuminate\Support\Facades\Log;
3
4class AppServiceProvider extends ServiceProvider
5{
6 public function boot()
7 {
8 DB::listen(function ($query) {
9 $location = collect(debug_backtrace())->filter(function ($trace) {
10 return !str_contains($trace['file'], 'vendor/');
11 })->first(); // grab the first element of non vendor/ calls
12
13 $bindings = implode(", ", $query->bindings); // format the bindings as string
14
15 if ($query->time < 1) {
16 return;
17 }
18
19 Log::channel('queries')->info("
20 ------------
21 Sql: $query->sql
22 Bindings: $bindings
23 Time: $query->time
24 File: {$location['file']}
25 Line: {$location['line']}
26 ------------
27 ");
28 });
29 }
30}
If this post was enjoyable or useful for you, please share it! If you have comments, questions, or feedback, you can email my personal email. To get new posts, subscribe use the RSS feed.