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

标签 logging laravel-5

我想用所有参数和生成响应所需的时间记录到达我网站的每个请求。该网站是在 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/

相关文章:

Laravel 5 CORS 中间件不适用于路由组

javascript - 在 Bootstrap 模式中实现无限滚动?

带有回调函数的 Python 记录器

python-3.x - 将日志添加到 Airflow 日志

java - 如何使用 Slf4j 的 Logback 实现通过 Spring 记录 SOAP 客户端消息

php - date_add() 期望参数 1 为 DateTime,给定字符串

mysql - Laravel 5.2 Eloquent 关系

laravel-5 - 仅可邮寄的邮件可以排队

python - 如何使用 logstash 和 elastic 配置 native python 日志记录库?

java - Elasticsearch 中的 log4j 升级