Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Correct way to get server response time in Laravel

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?

like image 938
John Bupit Avatar asked Jul 24 '15 20:07

John Bupit


2 Answers

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 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.

like image 126
John Bupit Avatar answered Sep 29 '22 03:09

John Bupit


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);
    }
    ...
}
like image 25
mp31415 Avatar answered Sep 29 '22 04:09

mp31415