How to Log All SQL Queries in Laravel

1 3,691

In this article, we will discuss “How to Log All SQL Queries in Laravel”. As we know, Laravel provides rich features and flexibility to make development easy. SQL Query Logging is the most common way to debug any application. Today, I will explain to you to Log all SQL Queries in your Laravel application.

There are multiple ways to create SQL Query Log.

Default Log file

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”.

use DB;
use Log;
...

// Add in boot function
DB::listen(function($query) {
    Log::info(
        $query->sql,
        $query->bindings,
        $query->time
    );
});

Create a custom query log file

Log SQL queries in the custom “query.log” file under the “storage/logs” directory.

use DB; // Illuminate\Support\Facades\DB;
use File; // Illuminate\Support\Facades\File;
...

// Add in boot function
DB::listen(function($query) {
    File::append(
        storage_path('/logs/query.log'),
        '[' . date('Y-m-d H:i:s') . ']' . PHP_EOL . $query->sql . ' [' . implode(', ', $query->bindings) . ']' . PHP_EOL . PHP_EOL
    );
});

Whenever the model executes then each time query is logged in the “query.log” file. And, log data looks like:

[2020-01-09 10:24:06]
select * from "users" where "id" = ? limit 1 [7]

[2020-01-09 10:25:04]
select "type" from "in_item" where "code" = ? and "vendor_id" = ? order by "id" desc [400000132365, 1]

Final Words

I hope you have enjoyed this tutorial, Today we’ve explored “How to Log All SQL queries in Laravel”. You can use this knowledge in your projects. If you have any query please feel free to add in the comment area 😉


You may like:

Brief Understanding Laravel Scopes

Handle Logging in Laravel

How to Handle Content Scraping in Laravel

How to Handle Content Scraping with Pagination in Laravel

1 Comment
  1. Guido Donnari says

    Another way to do query logging is to register a listener on app/Providers/EventServiceProvider.php

    for example:
    ‘Illuminate\Database\Events\QueryExecuted’ => [
    ‘App\Listeners\QueryExecutedListener’
    ]

    Then in your App\Listeners\QueryExecutedListener do the query logging:

    public function handle(QueryExecuted $query) {
    Log::debug(__METHOD__, [‘SQL’ => $query->sql]);
    Log::debug(__METHOD__, [‘bindings’ => $query->bindings]);
    Log::debug(__METHOD__, [‘time’ => $query->time]);
    }

Leave A Reply

Your email address will not be published.