Home > Net >  best way to log every request/response
best way to log every request/response

Time:11-11

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?

CodePudding user response:

You might want to leverage the ResponseReceived event. We can create a LogResponseReceived listener:

use Illuminate\Http\Client\Events;

class LogResponseReceived
{
    public function handle(ResponseReceived $event)
    {
        if ($event->request->method() == 'POST' && $event->request->url() == $yourUrl && $response->status() == $yourStatusCode) {
            // Log the data.
        }
    }
}

In addition, you can use laravel/telescope, But that is going to log every request.

CodePudding user response:

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;
    }
}

CodePudding user response:

hi for this not really need to create a new table. you can use laravel logging. it's up to you to create daily logs or a single log file. here are some examples depending on the type of log you want to save

use Illuminate\Support\Facades\Log;

Log::warning('User is accessing something', ['user' => Auth::user()]);
Log::info('User is accessing ', ['user' => Auth::user()]);
Log::emergency($message); 
Log::alert($message);
Log::critical($message); 
Log::error($message); 
Log::notice($message); 
Log::debug($message);

example

public function index(Request $request)
  {
    $todos = Todo::all();
    Log::warning('User is accessing ', ['user' => Auth::user()]);
    return view('dashboard')->with(['todos' => $todos]);
  }
  • Related