In this tutorial you will learn about the Store Log Of Eloquent SQL Queries In Laravel 8 and its application with practical example.
In this article, I’ll show you how to Store Log of Eloquent SQL Queries In Laravel 8. In this step by step tutorial I’ll explain laravel 8 Store Log of Eloquent SQL Queries. I’ll also show you to Store Log of Eloquent SQL Queries In Laravel.
Store Log Of Eloquent SQL Queries In Laravel 8
Developing a laravel application you come to situations where you may require to log SQL Query. Logging of SQL Queries helps to debug errors and make development easy.
Store In Default Log File
In Laravel, there is default log file located at storage/logs/laravel.log. In this example we will be going to store SQL log in laravel’s default log file. Let’s open AppServiceProvider.php file from app/Providers folder and put this code to boot() method:
app/Providers/AppServiceProvider.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
<?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 ); }); } } |
Laravel 8 Create A Custom Log File
We can also create a custom log file to store log data. In this example we will be creating a custom log file. Create query.log file in the storage/logs folder. In the boot() method of AppServiceProvider.php file put the following code:
app/Providers/AppServiceProvider.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
<?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 ); }); } } |
storage/logs
1 2 |
[2021-11-25 10:52:20] local.INFO: select * from `users` [2021-11-25 10:53:45] local.INFO: select * from `users` limit 5 offset 0 |