DEV Community

Paulund
Paulund

Posted on • Originally published at paulund.co.uk

9

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

Postgres on Neon - Get the Free Plan

No credit card required. The database you love, on a serverless platform designed to help you build faster.

Get Postgres on Neon

Top comments (2)

Collapse
 
snehalkadwe profile image
Snehal Rajeev Moon

Nice article, good to know this.

Collapse
 
bayuuv profile image
Bayu Surya

nice

Billboard image

Try REST API Generation for Snowflake

DevOps for Private APIs. Automate the building, securing, and documenting of internal/private REST APIs with built-in enterprise security on bare-metal, VMs, or containers.

  • Auto-generated live APIs mapped from Snowflake database schema
  • Interactive Swagger API documentation
  • Scripting engine to customize your API
  • Built-in role-based access control

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay