有时,我们调试需要记录用户对数据库的查询记录。mysql 免费版没有这个功能,但是我们可以通过laravel 监听事件(event)来达到目的
第一步:通过命令新建文件
php artisan make:listenter SqlQueryListener
第二步:编辑 新建的这个文件
<?php namespace AppListeners; use IlluminateQueueInteractsWithQueue; use IlluminateContractsQueueShouldQueue; use IlluminateDatabaseEventsQueryExecuted; use IlluminateSupportFacadesLog; class SqlQueryListener { /** * Create the event listener. * * @return void */ public function __construct() { // } /** * 记录SQL查询日志 * * @param object $event * @return void */ public function handle(QueryExecuted $event) { try { if (env(‘API_DEBUG‘) == true) { $sql = str_replace("?", "‘%s‘", $event->sql); foreach ($event->bindings as $i => $binding) { if ($binding instanceof DateTime) { $event->bindings[$i] = $binding->format(‘‘Y-m-d H:i:s‘‘); } else { if (is_string($binding)) { $event->bindings[$i] = "‘$binding‘"; } } } $log = vsprintf($sql, $event->bindings); $log = $log . ‘ [ RunTime:‘ . $event->time . ‘ms ] ‘; /*记录sql查询信息到日志,记录日志并自定义位置*/ Log::useDailyFiles(storage_path(‘logs/job/error.log‘));
Log::info($log);
} } catch (Exception $exception) { } } }
第三步:在providers目录下EventServiceProvider设置
protected $listen = array( ................... ‘IlluminateDatabaseEventsQueryExecuted‘ => [ ‘AppListenersQueryListener‘, ], );