106 words, 1 min read
    
  
  First, add a logging channel in config/logging.php:
return [
    'channels' => [
        'queries' => [
            'driver' => 'daily',
            'path' => storage_path('logs/queries.log'),
            'level' => 'debug',
            'days' => 28,
        ],
    ],
];
After that, update your AppServiceProvider in app/Providers/AppServiceProvider.php:
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
class AppServiceProvider extends ServiceProvider
{
    public function boot()
    {
        DB::listen(function ($query) {
            $location = collect(debug_backtrace())->filter(function ($trace) {
                return !str_contains($trace['file'], 'vendor/');
            })->first(); // grab the first element of non vendor/ calls
            $bindings = implode(", ", $query->bindings); // format the bindings as string
            if ($query->time < 1) {
                return;
            }
            Log::channel('queries')->info("
                    ------------
                    Sql: $query->sql
                    Bindings: $bindings
                    Time: $query->time
                    File: {$location['file']}
                    Line: {$location['line']}
                    ------------
            ");
        });
    }
}
  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.