我创建了一个 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 inbootstrap/autoload.php
which is the very first file included frompublic/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 beforeapp->terminate()
will be called, so you should get a pretty good computation of execution time.
关于php - 在 Laravel 中获取服务器响应时间的正确方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31619350/