Reputation: 2683
I have a logging function that tracks pageloads. I would like to add that to every route that I already have in Symfony.
Currently I am doing it like this:
/**
* @Route("/test", name="test")
*/
public function testAction(Request $request)
{
/* Function to register pageload */
$this->get('statsd')->countMetric('visitor.'.$request->get('_route'));
return $this->render('default/indexFull.html.twig', array());
}
I could of course add that line to every route, but since I am new to Symfony I thought there might be a more elegant approach?
Any hint appreciated!
Upvotes: 3
Views: 2024
Reputation: 41934
Symfony triggers events during the handling of a request. One of these events is the kernel.request
event, which is executed before each controller.
Be aware that the router will do the matching during this event as well, so you need to make sure your listener is executed after the router listener. This can be done by using priorities.
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
class CountMetricLogger
{
// ...
public function logVisit(GetResponseEvent $event)
{
$this->statsd->countMetric('visitor.'.$event->getRequest()->get('_route'));
}
}
# app/config/services.yml
app.metric_logger:
class: AppBundle\EventListener\CountMetricLogger
arguments: ['@statsd']
tags:
- { name: kernel.event_listener, event: kernel.request, method: logVisit }
More information:
Upvotes: 6