Logging request and response

Hi everyone!

I’m building an API and, as a feature, I would like to provide the admin a log of every request received and it’s corresponding response. This log is a table in my database and in Cake model.
What do you guys think is the best approach to handle this?

Saludos,

Are you using the middleware-based app skeleton? If so, this very much seems like the kind of thing that a small piece of middleware could do for you.

Hi Zuluru,
Thanks for your answer. I am working indeed with a middleware based app skeleton. Since I never really used the middleware, I wanted to collect some expertise, but I suspected it was the right layer for the job.
Saludos,

Hi Zuluru and everyone,

In order to provide some feedback and, also, just in case someone else bumps with this same need, this is the code that worked for me:

<?php
namespace App\Middleware;

use Cake\Http\Cookie\Cookie;
use Cake\I18n\Time;
use App\Model\Table\WmsIncomingCommunicationsTable;
use Cake\ORM\TableRegistry;


class RequestLoggingMiddleware
{
    public function __invoke($request, $response, $next)
    {
        // Calling $next() delegates control to the *next* middleware
        // In your application's queue.
        $response = $next($request, $response);
        
        $value = $request->ContentType();
        $url = $request->getRequestTarget();
       

        
        if ($value=="application/json") {
            $config = TableRegistry::getTableLocator()->exists('WmsIncomingCommunications')         ? [] : ['className' => WmsIncomingCommunicationsTable::class];
            $this->WmsIncomingCommunications =    TableRegistry::getTableLocator()->get('WmsIncomingCommunications', $config);
            
            $data = [
                'model' => 'None',
                'identifier' => 1,
                'url' => $url,
                'status' => $response->getStatusCode(),
                'request' => 'Data: '.$request->getBody()->__toString(),
                'response' => $response->getBody()->__toString(),
            ];
            
            $entity = $this->WmsIncomingCommunications->newEntity($data);
            
            $this->WmsIncomingCommunications->save($entity);}
        
        $request->getBody();

        return $response;
    }
}
?>

The WmsIncomingCommunications is the specific log model I made.

Saludos,

If the api uses authentication, will you not log and store as a plain text credentials ?

Hi Marceli,

It shouldn’t, because the authentication data won’t be neither in the request body nor the response body, but in the headers.

Maybe I’m wrong, I haven’t added the authentication features yet.

Saludos,

Sorry for delay.

I think that approach is correct - using middleware for such things is always best choice, and you can always exclude from logs authentication related calls.

1 Like