You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
73 lines
2.2 KiB
73 lines
2.2 KiB
3 weeks ago
|
<?php
|
||
|
|
||
|
namespace App\Http\Middleware;
|
||
|
|
||
|
use Closure;
|
||
|
use Illuminate\Http\JsonResponse;
|
||
|
use Illuminate\Http\Request;
|
||
|
use Illuminate\Http\Response;
|
||
|
|
||
|
class RecordApiLog
|
||
|
{
|
||
|
/**
|
||
|
* @param Request $request
|
||
|
* @param Closure $next
|
||
|
* @return mixed
|
||
|
*/
|
||
|
public function handle(Request $request, Closure $next): mixed
|
||
|
{
|
||
|
$request->attributes->set('start_time', microtime(true));
|
||
|
|
||
|
return $next($request);
|
||
|
}
|
||
|
|
||
|
/**
|
||
|
* @param Request $request
|
||
|
* @param Response|JsonResponse $response
|
||
|
*/
|
||
|
public function terminate(Request $request, Response|JsonResponse $response): void
|
||
|
{
|
||
|
//结束时间
|
||
|
$end = microtime(true);
|
||
|
$diff = $end - $request->attributes->get('start_time');
|
||
|
|
||
|
$ip = json_encode($request->ips(),256);
|
||
|
|
||
|
if ($response instanceof JsonResponse) {
|
||
|
$responseStr = $this->getJsonResponseStr($response);
|
||
|
} else {
|
||
|
$responseStr = $this->getResponseStr($response);
|
||
|
}
|
||
|
|
||
|
recordLog('RecordApiUse', implode("\n", [
|
||
|
'请求地址: '. $ip. '|'. $request->method(). '|'. $request->url(),
|
||
|
'请求入参: '. json_encode(request()->all(), JSON_UNESCAPED_UNICODE),
|
||
|
'请求出参: '. $responseStr,
|
||
|
'耗时: '. sprintf("%.6f", $diff). 's'
|
||
|
]));
|
||
|
}
|
||
|
|
||
|
/**
|
||
|
* 获取响应字符串
|
||
|
* @param Response $response
|
||
|
* @return string
|
||
|
*/
|
||
|
protected function getResponseStr(Response $response): string
|
||
|
{
|
||
|
return PHP_EOL. sprintf('HTTP/%s %s %s', $response->getProtocolVersion(), $response->getStatusCode(), Response::$statusTexts[$response->getStatusCode()]). PHP_EOL.
|
||
|
$response->headers. PHP_EOL.
|
||
|
json_encode($response->getContent(), JSON_UNESCAPED_UNICODE);
|
||
|
}
|
||
|
|
||
|
/**
|
||
|
* 获取json相应字符串
|
||
|
* @param JsonResponse $response
|
||
|
* @return string
|
||
|
*/
|
||
|
protected function getJsonResponseStr(JsonResponse $response): string
|
||
|
{
|
||
|
return PHP_EOL. sprintf('HTTP/%s %s %s', $response->getProtocolVersion(), $response->getStatusCode(), Response::$statusTexts[$response->getStatusCode()]). PHP_EOL.
|
||
|
$response->headers. PHP_EOL. json_encode($response->getData(), JSON_UNESCAPED_UNICODE);
|
||
|
}
|
||
|
}
|