我正在尝试使用Symfony2中的事件侦听器记录请求和响应。
我已注册以下服务:
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);
}
}
使用此配置:
example.response_listener:
class: Example\ServerBundle\EventListener\LoggerListener
arguments: ["@doctrine.odm.mongodb.document_manager"]
tags:
- { name: kernel.event_listener, event: kernel.response, method: onKernelResponse }
如何在此操作中获取请求和响应?如果我将注入请求服务,我想我可以得到请求。但是回应呢?
答案 0 :(得分:7)
您可以read here,kernel.response
事件对象传递给您的侦听器FilterResponseEvent
。此对象具有getRequest
和getResponse
方法。所以你的代码应该是这样的:
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.
}