Laravel Log DB Queries

paulund

Paulund

Posted on April 29, 2024

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

💖 💪 🙅 🚩
paulund
Paulund

Posted on April 29, 2024

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

Laravel Log DB Queries
laravel Laravel Log DB Queries

April 29, 2024