有时候功能模块编写完成之后,运行速度还是很慢,如果开启了这个日志。那么我们就可以在日志里面查看到每一天执行的sql耗时,可以更加快捷的定位到问题。
具体打开的方法如下:
在app/Providers/EventServiceProvider.php里面增加
'Illuminate\Database\Events\QueryExecuted' => [
'App\Listeners\QueryListener',
],
在app/Listeners增加QueryListener.php
<?phpnamespace App\Listeners;use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Database\Events\QueryExecuted;
use Monolog\Logger;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Support\Facades\Log;
use Monolog\Handler\RotatingFileHandler;class QueryListener
{
/**
* Create the event listener.
*
* @return void
*/
public function __construct()
{
//
} /**
* Handle the event.
*
* @param QueryExecuted $event
* @return void
*/
public function handle(QueryExecuted $event)
{
try{
if (env('APP_DEBUG') == true) {
$this->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里面
发表评论 取消回复