Symfony2 logging 404 errors

余生长醉 提交于 2019-11-29 15:48:53

问题


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)



来源:https://stackoverflow.com/questions/7081008/symfony2-logging-404-errors

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!