skip to Main Content

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?

3

Answers


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

    use IlluminateHttpClientEvents;
    
    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.

    Login or Signup to reply.
  2. 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 IlluminateSupportFacadesLog;

    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]);
      }
    
    Login or Signup to reply.
  3. 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 AppHttpMiddleware;
    
    use Closure;
    use IlluminateSupportFacadesLog;
    
    class RequestLogger
    {
        /**
         * Handle an incoming request.
         *
         * @param  IlluminateHttpRequest  $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;
        }
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search