Posted on under Laravel by Owen Conti.
Here's a quick snippet to get HTTP request logging setup quickly in Laravel:
1<?php 2 3namespace App\Http\Middleware; 4 5use Closure; 6use Illuminate\Support\Facades\Log; 7 8class RequestLogger 9{10 /** @var int */11 private $startTime;12 13 /**14 * Handle an incoming request.15 *16 * @param \Illuminate\Http\Request $request17 * @param \Closure $next18 * @return mixed19 */20 public function handle($request, Closure $next)21 {22 $this->startTime = round(microtime(true) * 1000);23 24 return $next($request);25 }26 27 public function terminate($request, $response)28 {29 $user = $request->user();30 $userId = $user ? $user->id : 0;31 32 $token = $user && $user->token() ? $user->token()->id : null;33 34 $method = strtoupper($request->getMethod());35 36 $statusCode = $response->getStatusCode();37 38 $uri = $request->getPathInfo();39 40 $bodyAsJson = json_encode($request->except(['password', 'password_confirmation']));41 42 $contentType = $response->headers->get('Content-Type');43 44 $runTime = round(microtime(true) * 1000) - $this->startTime;45 46 Log::info("{$statusCode} {$runTime}ms {$method} {$contentType} {$uri} | User: {$userId} | Token: {$token} | {$bodyAsJson}");47 }48}
Because both the
handle
and
terminate
methods access the
$this->startTime
variable, we need to make sure we receive the same instance of the middleware in both methods. To do this, you need to register the middleware as a singleton in the
boot
method of your
AppServiceProvider
:
1<?php2 3public function boot()4{5 $this->app->singleton(\App\Http\Middleware\RequestLogger::class);6}
Don't forget to add the middleware to the
$middleware
array in
App\Http\Kernel.php
!
Credit to https://github.com/spatie/laravel-http-logger for some of the lines.
Hopefully you found this article useful! If you did, share it on X!
Found an issue with the article? Submit your edits against the repository.