John Bupit
John Bupit

Reputation: 10618

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?

Upvotes: 16

Views: 23229

Answers (2)

mp31415
mp31415

Reputation: 6689

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);
    }
    ...
}

Upvotes: 1

John Bupit
John Bupit

Reputation: 10618

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.

Upvotes: 31

Related Questions