In laravel 5.7 all logfiles are generated in app/storage/logs. By default log is generated on daily basis. So to keep track of any issues it can help. But sometimes database query logs is needed when it's difficult to find out the bug in database level.
When I encountered this in a project, I decided to write this post in simple steps on this topic.

It will help you in logging every database queries on each request.

Step 1: Create a file named as logger.php in app folder & put the following codes.


use Monolog\Logger;
use Monolog\Handler\StreamHandler;
if( Config::get('app.debug') === true ){
    DB::listen(function($sql, $bindings, $time){
        $logFile = storage_path('logs/dbquery.log');
        $monolog = new Logger('log');
        $monolog->pushHandler(new StreamHandler($logFile), Logger::INFO);
        $monolog->info($sql, compact('bindings', 'time'));
    });
}

Step 2: Now you have to make some code changes in global.php file in location app/start/global.php.
Add the following code at the end of global.php file.


require_once app_path('logger.php');

Step 3: Check your application for a new file dbquery.log has been created. Now open "app\storage\logs\dbquery.log".  All db queries logs will be placed here.

Enjoy Laravel db log!!

Comments