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:
Table of Contents
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:
<?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. ?
Comment
Preview may take a few seconds to load.
Markdown Basics
Below you will find some common used markdown syntax. For a deeper dive in Markdown check out this Cheat Sheet
Bold & Italic
Italics *asterisks*
Bold **double asterisks**
Code
Inline Code
`backtick`Code Block```
Three back ticks and then enter your code blocks here.
```
Headers
# This is a Heading 1
## This is a Heading 2
### This is a Heading 3
Quotes
> type a greater than sign and start typing your quote.
Links
You can add links by adding text inside of [] and the link inside of (), like so:
Lists
To add a numbered list you can simply start with a number and a ., like so:
1. The first item in my list
For an unordered list, you can add a dash -, like so:
- The start of my list
Images
You can add images by selecting the image icon, which will upload and add an image to the editor, or you can manually add the image by adding an exclamation !, followed by the alt text inside of [], and the image URL inside of (), like so:
Dividers
To add a divider you can add three dashes or three asterisks:
--- or ***

Comments (0)