记录 Laravel 中的操作和执行时间

sid*_*606 4 logging laravel-5

我想用所有参数和生成响应所需的时间记录到达我网站的每个请求。该网站是在 Laravel 5 中构建的。我确实尝试了不同的方法,但没有运气。我的主要问题是如何获得总执行时间。

谢谢

Jav*_*olz 9

在 HTTP 响应已经发送到浏览器之后,您可以使用可终止中间件来记录它。

要获得总时间,您可以将 的结果microtime(true)与 laravel 常数进行比较LARAVEL_START。该常量定义在bootstrap/autoload.php,框架的入口点

例如,这里有一个中间件,它会同时记录 HTTP 标头和系统记录响应时间。由于您可以访问$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,
            ]);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)