Issue
I have an authentication issue on a production server, the issue is very likely to be non-code related but rather an IT configuration issue...
To prove this I would like to check if API Platform receives the Authorization header when trying to fetch data. I have not found anything about logs in the API Platform documentation. What is the right way of logging API requests and their headers using the Symfony logging systems, knowing that I don't have access to the actual controller code as it is purely configured using the APIRessource annotation on entities ?
To be clear, everything works fine in local, I'm not looking for a solution to my problem here, just a clean way to change the log format or add logs to incoming request using API Platform.
Solution
You can create a listener for the kernel.terminate event, that would be logging request and response data. Something like this.
monolog.yaml
monolog:
handlers:
request_log:
type: rotating_file
max_files: 90
level: debug
path: '%kernel.logs_dir%/request/%kernel.environment%.log'
channels: request_log
services.yaml
App\EventListener\LogRequestAndResponseEventListener:
tags:
- { 'name': 'monolog.logger', 'channel': 'request_log' }
- { 'name': 'kernel.event_listener', 'event': 'kernel.terminate', 'method': 'onKernelTerminate' }
listener
namespace App\EventListener;
use Psr\Log\LoggerInterface;
use Symfony\Component\HttpKernel\Event\TerminateEvent;
class LogRequestAndResponseEventListener
{
private $logger;
public function __construct(LoggerInterface $logger)
{
$this->logger = $logger;
}
public function onKernelTerminate(TerminateEvent $event)
{
$request = $event->getRequest();
$response = $event->getResponse();
$this->logger->info('data', [
'route' => $request->getMethod() . ' ' . $request->getRequestUri(),
'status' => $response->getStatusCode(),
'request body' => $request->request->all(),
'response' => json_decode($response->getContent(), true),
'headers' => $request->headers->all(),
]);
}
}
Answered By - Ihor Kostrov
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.