创建监听器
php artisan make:listener QueryListener --event=Illuminate\Database\Events\QueryExecuted
打开app/Providers/EventServiceProvider.php
添加引导
protected $listen = [
'Illuminate\Database\Events\QueryExecuted' => [
'App\Listeners\QueryListener',
]
];
打开app/Listeners/QueryListener
#引入log
use Illuminate\Support\Facades\Log;
#handle方法添加代码:
public function handle(QueryExecuted $event)
{
if (env('APP_DEBUG')) {
$sql = str_replace("?", "'%s'", $event->sql);
$log = vsprintf($sql, $event->bindings);
$log = '[' . date('Y-m-d H:i:s') . '] ' . $log . PHP_EOL;
$logDir = storage_path('logs/sql');
// if (!is_dir($logDir)) {
// mkdir($logDir, 0777, true);
// }
file_put_contents($logDir, $log, FILE_APPEND);
//Log::channel('sql')->info($log);
#未添加sql日志通道
/*
'sql'=>[
'driver' => 'daily',
'level' => 'debug',
'path' => storage_path('logs/sql/log.log'),
],
*/
}
}
补充-添加日志通道
在写入日志使用Log::channel('sql')->info($log);
需要配置下日志记录通道
在config/logging.php
加入以下内容:
'sql'=>[
'driver' => 'daily',
'level' => 'debug',
'path' => storage_path('logs/log.log'),
],
评论