The right way to get server response time in Laravel

I created a terminable middleware that sends a request to Google Analytics. One of the attributes I'm sending is server response time. Here is how I do it:

In \App\Http\KernelI add SendAnalyticsmiddleware:

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

And the middleware SendAnalyticslooks like this:

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 it always shows 0.0. What would be the right way to show server response time?

+4
source share
2 answers

I have used microtime(true) - LARAVEL_START. It seems to give a fairly accurate response time.

As Bogdan mentions in a comment:

LARAVEL_START bootstrap/autoload.php, , public/index.php, , . , app->terminate() , .

+8

, . terminate. ( , , 200 ). handle, , , .

class SendAnalytics implements TerminableMiddleware {

    protected $startTime;

    public function handle($request, Closure $next) {
        $this->startTime = microtime(true);
        return $next($request);
    }
    ...
}
0

Source: https://habr.com/ru/post/1599581/


All Articles