有时候功能模块编写完成之后,运行速度还是很慢,如果开启了这个日志。那么我们就可以在日志里面查看到每一天执行的sql耗时,可以更加快捷的定位到问题。
具体打开的方法如下:
在app/Providers/EventServiceProvider.php里面增加
'Illuminate\Database\Events\QueryExecuted' => [ 'App\Listeners\QueryListener', ],
在app/Listeners增加QueryListener.php
recordLog($event, 'logs/sql/sql.log'); } }catch (\Exception $exception){ Log::error('log sql error:'.$exception->getMessage()); } } protected function recordLog($event, $sqlFile) { $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 ] '; (new Logger('sql'))->pushHandler(new RotatingFileHandler(storage_path($sqlFile)))->info($log); }}
打开之后,我们以后的业务执行过的sql都会保存在storage/logs/sql里面
来源地址:https://blog.csdn.net/MrEahon/article/details/127889729