php - 在 Laravel 中获取服务器响应时间的正确方法

标签 php laravel laravel-5

我创建了一个 terminable middleware向 Google Analytics 发送请求。我发送的属性之一是服务器响应时间。以下是我的做法:

\App\Http\Kernel 中,我添加了 SendAnalytics 中间件:

class Kernel extends HttpKernel {
    ...
    protected $middleware = [
        'Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode',
        ...
        'App\Http\Middleware\SendAnalytics',
    ];
}

SendAnalytics 中间件如下所示:

class SendAnalytics implements TerminableMiddleware {

    protected $startTime;

    public function __construct() {
        $this->startTime = microtime(true);
    }

    public function handle($request, Closure $next) {
        return $next($request);
    }

    public function terminate($request, $response) {
        $responseTime = microtime(true) - $this->startTime;
        /* I send a request to Google here, using their Measurement Protocol */
        // Dying for debugging purposes
        dd($responseTime); // Always prints 0.0
    }
}

但这总是显示 0.0。显示服务器响应时间的正确方法是什么?

最佳答案

我使用了 microtime(true) - LARAVEL_START。似乎给出了相当准确的响应时间。

正如 Bogdan 在评论中提到的:

The LARAVEL_START constant is defined in bootstrap/autoload.php which is the very first file included from public/index.php, so this makes it the first statement to be executed. If you place the middleware last on the list, its terminate method will be the last one executed before app->terminate() will be called, so you should get a pretty good computation of execution time.

关于php - 在 Laravel 中获取服务器响应时间的正确方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31619350/

相关文章:

php - 如何在行和列反转时显示数据库中的数据

php - 多个下拉菜单中的数千个项目

php - 如何将自定义验证消息传递给 Laravel 中的 cviebrock/image-validator?

forms - 将编辑按钮从表格链接到 Laravel 编辑表单

php - 如何转换 bigint 以防止 php 中的 sql 注入(inject)?

php - 在 Laravel 4 中找不到库类

mysql - A.* 不在 Laravel 查询生成器上带有左连接的 GROUP BY 中

PHP artisan 突然不能用了

mysql - 如何在 Laravel Eloquent 地解决对 json 数据的 case-sensitive where like 语句?