3

I log some of the api requests. It is currently done sync and I would like to process this DB call async to allow faster response times for the actual api call. The way to do this in Laravel seems to be the queue/job system. However I am not sure if this is also the case for a simple log entry added to the DB:

$log = new Log();
$log->request = $request->all();
$log->response = $response;
$log->save();

So, should I create a job and dispatch it for this? Seems like overkill to have a queue worker and all the boilerplate just for this.

EDIT: I just realized that this might be stupid anyways, since the queue also needs to write to the jobs table. So queuing something requires 1 DB query, right? So there is probably no point to use a job for a single query action.

Is there some other way to defer the execution of the logging until after the response?

Chris
  • 13,100
  • 23
  • 79
  • 162
  • First thing you need to do is determine how much overhead this *really* adds to each request. In all likelihood serializing and queuing might be exactly as slow – apokryfos Oct 12 '17 at 14:53

2 Answers2

3

The best thing to do is to just log within a terminatable middleware.

class LogMiddleware {
      public function handle($request, $next) {
            return $next($request); //Passthrough
      }
      public function terminate($request,$response) {
           $log = new Log();
           $log->request = $request->all();
           $log->response = $response;
           $log->save();
      }
}

In your Kernel.php

//...
protected $middlewareGroups [
     //...
     "api" => [
           //Other middleware
           LogMiddleware::class
      ]
];

Now every API request will be logged. This will happen after the response is sent to the client. The request/response cycle will not terminate faster, but the client will receive the response before the logging occurs (and so will not perceive any logging delay).

apokryfos
  • 38,771
  • 9
  • 70
  • 114
0

You can use a different queue driver such as Redis and then fire an event that implements the ShouldQueue interface every time an api request is made (or every time you wish to log an api request).

Naxon
  • 1,354
  • 4
  • 20
  • 40