我想用所有参数和生成响应所需的时间记录到达我网站的每个请求。该网站是在 Laravel 5 中构建的。我确实尝试了不同的方法,但没有运气。我的主要问题是如何获得总执行时间。
谢谢
最佳答案
您可以使用 Terminable Middleware在 HTTP 响应已经发送到浏览器后记录它。
要获得总时间,您可以比较 microtime(true)
的结果使用 Laravel 常量 LARAVEL_START
.该常量定义在 bootstrap/autoload.php
,框架的入口点
例如,这里有一个中间件,它会同时记录 HTTP header 和系统记录响应时间。由于您可以访问 $request
中的当前请求变量,您可以利用它来记录您想要的任何参数
<?php // File: app/Http/Middleware/MeasureResponseTime.php
namespace App\Http\Middleware;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
class MeasureResponseTime
{
/**
* Handle an incoming HTTP request.
*
* @param \Symfony\Component\HttpFoundation\Request $request
* @param \Closure $next
* @return \Symfony\Component\HttpFoundation\Response
*/
public function handle($request, \Closure $next)
{
$response = $next($request);
// Add response time as an HTTP header. For better accuracy ensure this middleware
// is added at the end of the list of global middlewares in the Kernel.php file
if (defined('LARAVEL_START') and $response instanceof Response) {
$response->headers->add(['X-RESPONSE-TIME' => microtime(true) - LARAVEL_START]);
}
return $response;
}
/**
* Perform any final actions for the request lifecycle.
*
* @param \Symfony\Component\HttpFoundation\Request $request
* @param \Symfony\Component\HttpFoundation\Response $response
* @return void
*/
public function terminate($request, $response)
{
// At this point the response has already been sent to the browser so any
// modification to the response (such adding HTTP headers) will have no effect
if (defined('LARAVEL_START') and $request instanceof Request) {
app('log')->debug('Response time', [
'method' => $request->getMethod(),
'uri' => $request->getRequestUri(),
'seconds' => microtime(true) - LARAVEL_START,
]);
}
}
}
关于logging - 记录 Laravel 中的操作和执行时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32839866/