Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

best way to log every request/response

Tags:

laravel

I have a POST API to create a register on the database. My goal is to be able to log every 4XX request (with the response) for another team to view that list/search the data, with the option to download the request JSON sent in that call.

What's the best way to archive that? Its just to create a logs table in the database?

like image 893
Viitor Avatar asked Oct 18 '25 15:10

Viitor


1 Answers

Telescope may not be a very logical choice for use in a production environment. You can find an answer to your problem with a simple middleware. If it is an endpoint that receives a lot of requests, logging to the database will not be performant enough. You can write to a different log file instead.

<?php

namespace App\Http\Middleware;

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

class RequestLogger
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        $response = $next($request);

        //here you can check the request to be logged
        $log = [
                 'URI' => $request->getUri(),
                 'METHOD' => $request->getMethod(),
                 'REQUEST_BODY' => $request->all(),
                 'RESPONSE' => $response->getContent()
               ];

        return $response;
    }
}
like image 148
bariskau Avatar answered Oct 20 '25 16:10

bariskau



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!