版权声明:未经允许不得转载。 https://blog.csdn.net/qq_35958788/article/details/83509338
简介
- 针对于 lumen,具体版本如下:
Laravel Framework Lumen (5.7.3) (Laravel Components 5.7.*)
实际操作(记录 sql 以及执行时间)
注册映射关系
- EventServiceProvider中注册事件与监听器之间的映射关系:
'App\Events\SqlRecorded' => [
'App\Listeners\RecordSqlNotification',
],
开启事件服务
- lumen 默认不开启,在
bootstrap/app.php
文件中注册
$app->register(App\Providers\EventServiceProvider::class);
创建事件 event
- 文件
app/Events/SqlRecorded.php
<?php
namespace App\Events;
use Illuminate\Support\Facades\DB;
class SqlRecorded extends Event
{
/**
* Create a new event instance.
*
* @return void
*/
public function __construct()
{
DB::connection()->enableQueryLog();
}
public function broadcastOn()
{
return [];
}
}
创建监听 listen
- 文件
app/Listeners/RecordSqlNotification.php
<?php
namespace App\Listeners;
use App\Events\SqlRecorded;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Support\Facades\DB;
class RecordSqlNotification
{
/**
* Create the event listener.
*
* @return void
*/
public function __construct()
{
//
}
/**
* Handle the event.
*
* @param SqlRecorded $event
* @return void
*/
public function handle(SqlRecorded $event)
{
$path = storage_path('logs') . DIRECTORY_SEPARATOR . 'sql-' . date('Y-m-d') . '.log';
$queries = $this->refactor();
file_put_contents($path, json_encode($queries) . "\n", FILE_APPEND);
}
public function refactor()
{
$queries = DB::getQueryLog();
foreach ($queries as &$query) {
$bindings = count($query['bindings']);
if ($bindings > 0) {
$search = array_fill(0, $bindings, '?');
$sql = str_replace($search, $query['bindings'], $query['query']);
$query['query'] = $sql;
}
$query = [
'query' => $query['query'],
'time' => $query['time']
];
}
return $queries;
}
}
访问控制器
public function event()
{
$event = new SqlRecorded();
$res = (new User())->where('username', 'Jerry')->where('gender', 1)->get();
/*分发事件,此时事件将被监听,以下两种方式都可以实现*/
event($event);
//event::fire($event);
}
结束
- 注册路由后即可访问控制方法,并将sql存入指定文件。