DEV Community

Paulund
Paulund

Posted on • Originally published at paulund.co.uk

Laravel Log DB Queries

In this article we're going to look at how you can log all database queries that are executed within your Laravel application.

There are multiple way in Laravel that help you with debugging your application, such as Debugbar and Telescope. But in this article we're going to look at using logging. As there are some cases where you may not want to use a third party package and want to quickly see what SQL queries are being executed. Such as debugging a command line script.

Default Logging

Laravel has some handle ways of logging in your application this is by using the Log Facade. This facade allows you to log messages to a file, database, slack, etc.

You can pair this with the Database facade using the listen method. This method allows you to listen for any queries that are executed and log them to the log file.

DB::listen(function ($query) {
    Log::info($query->sql, $query->bindings);
});
Enter fullscreen mode Exit fullscreen mode

It's as simple as placing this inside your applications AppServiceProvider and you'll be able to see all queries that are executed.

Custom Log File

If you want to log all queries to a separate log file you can do this by using the useFiles method on the Log facade.

DB::listen(function($query) {
    File::append(
        storage_path('/logs/query.log'),
        sprintf('[%s] %s [%s]%s%s', date('Y-m-d H:i:s'), $query->sql, implode(', ', $query->bindings), PHP_EOL, PHP_EOL)
    );
});
Enter fullscreen mode Exit fullscreen mode

This will log all queries to the storage/logs/query.log file.

Resources

Laravel Database: Documentation

Top comments (2)

Collapse
 
snehalkadwe profile image
Snehal Rajeev Moon

Nice article, good to know this.

Collapse
 
bayuuv profile image
Bayu Surya

nice