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?
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.
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With