Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Log request and response with Event Listener in Symfony2

I am trying to log a Request and Response with an Event listener in Symfony2.

I've registered the following Service:

class LoggerListener
{

    /**
     * @var \Doctrine\ODM\MongoDB\DocumentManager
     */
    private $documentManager;

    public function __construct(DocumentManager $documentManager)
    {

        $this->documentManager = $documentManager;
    }

    public function onKernelResponse(FilterControllerEvent $event)
    {
        $controller = $event->getController();

        if ( ! is_array($controller)) {
            return;
        }

        if ( ! $controller instanceof BaseAPIController) {
            return;
        }


        $log = new ServerRequestsLog();
        $log->setRequest($request);
        $log->setRequest($response);


    }
} 

with this configuration:

  example.response_listener:
      class: Example\ServerBundle\EventListener\LoggerListener
      arguments: ["@doctrine.odm.mongodb.document_manager"]
      tags:
          - { name: kernel.event_listener, event: kernel.response, method: onKernelResponse }

How can I get the Request and the Response in this action? I think I can get the Request if I will inject the Request service. but what about the response?

like image 901
Zain Zed Avatar asked Dec 28 '14 14:12

Zain Zed


1 Answers

As you can read here, kernel.response event object, that passed to your listener is FilterResponseEvent. This object has both getRequest and getResponse methods. So your code should look like:

public function onKernelResponse(FilterResponseEvent $event)
{
    $request = $event->getRequest();
    $response = $event->getResponse();

    $log = new ServerRequestsLog();
    $log->setRequest($request);
    $log->setRequest($response);
    //....Save it with document manager, etc.
}
like image 149
Ziumin Avatar answered Oct 11 '22 15:10

Ziumin