先上代码:
<?php
namespace App\Http\Middlewares;
use Closure;
use Illuminate\Support\Facades\DB;
class ProfilerMiddleware
{
public function handle($request, Closure $next)
{
$extension = extension_loaded('tideways');
if (! $extension) {
return $next($request);
}
tideways_enable(TIDEWAYS_FLAGS_CPU | TIDEWAYS_FLAGS_MEMORY);
$begin = microtime(true);
$query = [];
DB::listen(function ($sql) use (&$query){
$bindings = $sql->bindings;
foreach ($bindings as $i => $binding) {
if ($binding instanceof \DateTime) {
$bindings[$i] = $binding->format('\'Y-m-d H:i:s\'');
} else {
if (is_string($binding)) {
$bindings[$i] = "'$binding'";
}
}
}
// Insert bindings into query
$tmpQuery = str_replace(['%', '?'], ['%%', '%s'], $sql->sql);
$query[] = vsprintf($tmpQuery, $bindings);
});
$result = $next($request);
$end = microtime(true);
if ($end - $begin > env('APP_MAX_RESPONSE_TIME', 1)) {
$dir = storage_path('logs');
$file = 'profiler.' . route_name() . '.log';
$content = json_encode(tideways_disable());
file_put_contents($dir . '/' . $file, $content);
// Save the query to file
$logFile = fopen(storage_path('logs' . DIRECTORY_SEPARATOR . 'slow-db-query-' . date('Y-m-d') . '.log'), 'a+');
foreach ($query as $item){
fwrite($logFile, date('Y-m-d H:i:s') . ': ' . $item . PHP_EOL);
}
fclose($logFile);
}
return $result;
}
}
代码解释:
- 使用tideways扩展+中间件记录执行慢的接口和请求分析所需数据:首先lumen中的中间件会在执行代码中的$next($request)后,执行后续的全部操作,最终$result变量存储的是最终的response,而tideways是php分析代码执行的扩展
- 使用DB监听记录执行的SQL,并记录
中间件:https://blog.csdn.net/why444216978/article/details/103365336
tideways:https://blog.csdn.net/why444216978/article/details/103365063