Symfony2 logging 404 errors

2019-02-07 21:24发布

问题:

I need to be able to log/receive an email when a 404 error occurs. I can see in the docs how to set up a new template for these errors, but how do I catch them in the first place in my controller so that I can implement the logging/emailing logic?

回答1:

Maybe adding an event listener listening for the kernel.exception event would do it? Check out http://symfony.com/doc/current/book/internals.html#kernel-exception-event along with http://symfony.com/doc/current/reference/dic_tags.html#dic-tags-kernel-event-listener

A little example:

1) Create a custom Listener

//bundles/Acme/AcmeBundle/Listener/CustomListener.php

namespace Acme\AcmeBundle\Listener;
use Symfony\Component\EventDispatcher\Event;

public class CustomListener {
    public function onKernelException(Event $event) {
        //Get hold of the exception
        $exception = $event->getException();
        //Do the logging
        // ...
    }
}

2) Add the listener to your config

//config.yml
services:
    kernel.listener.your_listener_name:
        class: Acme\AcmeBundle\Listener\CustomListener
        tags:
            - { name: kernel.event_listener, event: kernel.exception, method: onKernelException }

To get hold of the logging or mailing (Swiftmailer) services, you might consider injecting them into the listener (http://symfony.com/doc/current/book/service_container.html#referencing-injecting-services)