Skip to content

Instantly share code, notes, and snippets.

@semiherdogan
Created November 14, 2023 13:04
Show Gist options
  • Save semiherdogan/49f3a58f825e1a220b2d75a1622e9c1e to your computer and use it in GitHub Desktop.
Save semiherdogan/49f3a58f825e1a220b2d75a1622e9c1e to your computer and use it in GitHub Desktop.
Laravel log response time middleware

# Response time logger middleware for laravel

Output:

200    GET /                        66,656ms       127.0.0.1   12:36:09
200    GET /users                  116,261ms       127.0.0.1   12:36:10
200    GET /projects                86,876ms       127.0.0.1   12:36:11
<?php
namespace App\Http\Middleware;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use Symfony\Component\HttpFoundation\Response;
class LogResponseTimeMiddleware
{
/**
* Handle an incoming request.
*/
public function handle(Request $request, \Closure $next): Response
{
return $next($request);
}
/**
* Log response
*/
public function terminate(Request $request, Response $response): void
{
$log = [
'code' => $response->getStatusCode(),
'method' => str_pad($request->method(), length: 7, pad_type: STR_PAD_LEFT),
'url' => str_pad($request->getRequestUri(), length: 22, pad_type: STR_PAD_RIGHT),
'time' => str_pad(number_format(
num: (microtime(true) - LARAVEL_START) * 1000,
decimals: 3,
decimal_separator: ',',
thousands_separator: '',
).'ms', length: 10, pad_type: STR_PAD_LEFT),
'ip' => str_pad($request->ip(), length: 15, pad_type: STR_PAD_LEFT),
'current_date' => str_pad(now()->format('H:i:s'), length: 10, pad_type: STR_PAD_LEFT),
];
Log::build([
'driver' => 'daily',
'path' => storage_path('logs/request_times.log'),
'formatter' => \Monolog\Formatter\LineFormatter::class,
'formatter_with' => [
'format' => "%message%\n",
],
])->debug(
implode(' ', $log)
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment