Creating simple Laravel API request logger

When you developing an API using laravel It is easier to debug api requests if you have a way to see api request and response parameters.

We can simply do that using a middleware.  You can create new middleware using artisan command

php artisan make:middleware LogRequests

And add below code to the file created.

<?php

namespace App\Http\Middleware;

use Closure;

class LogRequests
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        return $next($request);
    }
    
    public function terminate($request, $response)
    {
      // Execute after the HTTP response has been sent to the browser
    }

    protected function log($request,$response)
    {
    }

}

I have added two more functions named terminate and log.

In handle function i have recorded start time.

In terminate function i have recorded the end time and logged request data using the log function.

You can change the log function as per your needs.

Completed code looks like below.

<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Support\Facades\Log;

class LogRequests
{
    public function handle($request, Closure $next)
    {
        $request->start = microtime(true);

        return $next($request);
    }

    public function terminate($request, $response)
    {
        $request->end = microtime(true);

        $this->log($request,$response);
    }

    protected function log($request,$response)
    {
        $duration = $request->end - $request->start;
        $url = $request->fullUrl();
        $method = $request->getMethod();
        $ip = $request->getClientIp();

        $log = "{$ip}: {$method}@{$url} - {$duration}ms \n".
        "Request : {[$request->all()]} \n".
        "Response : {$response->getContent()} \n";

        Log::info($log);
    }
}

To run the middleware you should register your middleware on app/Http/Kernel.php file.

protected $middlewareGroups = [
    ...,
    'api' => [
        'bindings',
        'request_logger'
    ],
];

protected $routeMiddleware = [
    ...
    'request_logger' => \App\Http\Middleware\LogRequests::class
];

API requests should be logged in storage/logs/laravel.log file 

And you can Clear the log file using following linux command.

truncate -s 0 storage/logs/laravel.log

Let me know your ideas and suggestions in comments . Cheers !