Handle Query Logging – Laravel 5.6

2 2,125

In this article, we will discuss how to handle query logging in Laravel. I’m assuming you are much familiar with the Laravel as you are reading this. Laravel optionally log all queries that have been running in the current request in memory. There is some kind of method available for this. You can check official docs for migration, also get more article on Laravel here.

Query Logging

To get an array of the executed queries, you can use getQueryLog().

$log = DB::getQueryLog();

If, you want to maintain log file in storage/logs directory. You need to update your app/Providers/AppServiceProvider.php and update the boot() function.

<?php
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
use DB;

class AppServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        DB::listen(function($query) {
            Log::info(
                $query->sql,
                $query->bindings,
                $query->time
            );
        });
    }

    /**
     * Register any application services.
     *
     * @return void
     */
    public function register()
    {
        //
    }
}

Hope you like this article. Please feel free to add the comment if any query.

 

Leave A Reply

Your email address will not be published.

2 Comments
  1. Anatoly says

    man, your code is not correct, because it do not log a time. Log::info having two arguments, you giving them three (time is third), so time is no logging.

    1. Code Briefly says

      Hi Anatoly, Please add more details such as code snippet, example, or reference.