Store Log Of Eloquent SQL Queries In Laravel 8

Laravel 8 , Laravel 7 , Laravel , Laravel 6

Nicesnippets

497

25-10-2021


Store Log Of Eloquent SQL Queries In Laravel 8

Hi Dev,

This example is focused on Store Log of Eloquent SQL Queries In Laravel 8. step by step explain laravel 8 Store Log of Eloquent SQL Queries. i would like to show you Store Log of Eloquent SQL Queries In Laravel.

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:

example 1 : 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:

app/Providers/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

);

});

}

}

example 2 : 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:

app/Providers/AppServiceProvider.php

<?php

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:

storage/logs

[2021-10-25 10:52:20] local.INFO: select * from `users`

[2021-10-25 10:53:45] local.INFO: select * from `users` limit 5 offset 0

I hope it can help you...


Recommended Posts