I want to log every request that come to the my site with all the parameters and the time it need to generate the response. The site is build in Laravel 5. I did try different approaches but no luck. My main problem is in how to get the total execution time.
Thanks
Laravel logging is based on "channels". Each channel represents a specific way of writing log information. For example, the single channel writes log files to a single log file, while the slack channel sends log messages to Slack. Log messages may be written to multiple channels based on their severity.
You can see the generated log entries in storage/logs/laravel. log file.
By default, Laravel is configured to create a single log file for your application, and this file is stored in app/storage/logs/laravel. log .
You can use a Terminable Middleware to log the HTTP response after it has already been sent to the browser.
To get the total time you can compare the result of microtime(true)
with the laravel constant LARAVEL_START
. That constant is defined at bootstrap/autoload.php
, the entry point of the framework
For instance, here is a middleware that will log in both HTTP headers and system log the response time. Since you have access to the current request in the $request
variable you could leverage that to also log any parameters you want
<?php // File: app/Http/Middleware/MeasureResponseTime.php
namespace App\Http\Middleware;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
class MeasureResponseTime
{
/**
* Handle an incoming HTTP request.
*
* @param \Symfony\Component\HttpFoundation\Request $request
* @param \Closure $next
* @return \Symfony\Component\HttpFoundation\Response
*/
public function handle($request, \Closure $next)
{
$response = $next($request);
// Add response time as an HTTP header. For better accuracy ensure this middleware
// is added at the end of the list of global middlewares in the Kernel.php file
if (defined('LARAVEL_START') and $response instanceof Response) {
$response->headers->add(['X-RESPONSE-TIME' => microtime(true) - LARAVEL_START]);
}
return $response;
}
/**
* Perform any final actions for the request lifecycle.
*
* @param \Symfony\Component\HttpFoundation\Request $request
* @param \Symfony\Component\HttpFoundation\Response $response
* @return void
*/
public function terminate($request, $response)
{
// At this point the response has already been sent to the browser so any
// modification to the response (such adding HTTP headers) will have no effect
if (defined('LARAVEL_START') and $request instanceof Request) {
app('log')->debug('Response time', [
'method' => $request->getMethod(),
'uri' => $request->getRequestUri(),
'seconds' => microtime(true) - LARAVEL_START,
]);
}
}
}
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