I've created a terminable middleware that sends a request to Google Analytics. One of the attributes I send is the server response time. Here's how I do it:
In \App\Http\Kernel
I add the SendAnalytics
middleware:
class Kernel extends HttpKernel {
...
protected $middleware = [
'Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode',
...
'App\Http\Middleware\SendAnalytics',
];
}
And the SendAnalytics
middleware looks like:
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
}
}
But this always shows 0.0
. What would be the correct way to show the server response time?
I used microtime(true) - LARAVEL_START
. Seems to give a fairly accurate response time.
As Bogdan mentions in the comment:
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.
I noticed that in a single request life cycle middleware instance may be initialized more than once. The second time is right before terminate
call. That would explain zero time result (on my machine it was not zero but pretty close to it, while the actual request time was more like 200ms). The handle
method was obviously called only once and this is where start time must be recorded.
class SendAnalytics implements TerminableMiddleware {
protected $startTime;
public function handle($request, Closure $next) {
$this->startTime = microtime(true);
return $next($request);
}
...
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With