PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Sunday, January 23, 2022

[FIXED] API Platform Logging Headers from requests

 January 23, 2022     api-platform.com, logging, symfony, symfony4     No comments   

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
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing