Store Log of Eloquent SQL Queries In Laravel

avatar
Jan 27, 2021 · Article · 1 min, 361 words

To debug Laravel application, sometimes we SQL Query logging. In this article, I’m going to share how to keep log of all queries in Laravel. Let’s start:

Table of Contents

  1. Store in Default Log File
  2. Create a Custom Log File
  3. Preview

Store in Default Log File

Laravel’s default log file location is storage/logs/laravel.log. We are going to store SQL log in the file. Open AppServiceProvider.php file from app/Providers folder. Then add this code to boot() method:

AppServiceProvider.php
<?php

namespace App\Providers;

use DB;
use Log;
use Illuminate\Support\ServiceProvider;

class AppServiceProvider extends ServiceProvider
{
    // register() method

    public function boot()
    {
        // add this one
        DB::listen(function($query) {
            Log::info(
                $query->sql,
                $query->bindings,
                $query->time
            );
        });
    }
}

Create a Custom Log File

We can also create a custom log file to store log data. Let’s create query.log file in the storage/logs folder. In the boot() method of AppServiceProvider.php file, just add this code:

namespace App\Providers;

use DB;
use File;
use Illuminate\Support\ServiceProvider;

class AppServiceProvider extends ServiceProvider
{
    // register() method

    public function boot()
    {
        // add this one
        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
            );
        });
    }
}

Preview

Now open the log file from storage/logs folder and see output like:

[2021-01-27 10:52:20] local.INFO: select * from `users`
[2021-01-27 10:53:45] local.INFO: select * from `users` limit 5 offset 0 
That’s all, artisans. Thanks for reading. ?

Comments

No comments yet…