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); } }