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?

1
  • 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 Commented Oct 12, 2017 at 14:53

2 Answers 2

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).

Sign up to request clarification or add additional context in comments.

Comments

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).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.