How to log ZF2 controller exceptions

I am logging an instance of Zend \ Log for exceptions, in the end I will need all the system errors that are now sent to the file. However, it does not work in controllers, an exception is displayed in the view (or not, depending on display_exceptions ). I found this error , nobody seems to care about it. So I need a workaround. Is there a way to get controllers not to have my exceptions?

 'service_manager' => array( 'factories' => array( 'Logger' => function ($sm) use ($sRootDir) { $log = new Zend\Log\Logger(); $writer = new Zend\Log\Writer\Stream($sRootDir . '/temp/license.log'); $log->addWriter($writer); Zend\Log\Logger::registerErrorHandler($log); Zend\Log\Logger::registerExceptionHandler($log); return $log; }, ), 
+4
source share
1 answer

You can attach send errors to the event:

Module.php

 public function onBootstrap(MvcEvent $e) { $eventManager = $e->getApplication()->getEventManager(); $moduleRouteListener = new ModuleRouteListener(); $moduleRouteListener->attach($eventManager); /** * Log any Uncaught Errors */ $sharedManager = $e->getApplication()->getEventManager()->getSharedManager(); $sm = $e->getApplication()->getServiceManager(); $sharedManager->attach('Zend\Mvc\Application', 'dispatch.error', function($e) use ($sm) { if ($e->getParam('exception')){ $sm->get('Logger')->crit($e->getParam('exception')); } } ); } 

Example service configuration for a simple registrar

 'factories' => array( 'Logger' => function($sm){ $logger = new \Zend\Log\Logger; $writer = new \Zend\Log\Writer\Stream('./data/log/'.date('Ym-d').'-error.log'); $logger->addWriter($writer); return $logger; }, // ... ); 

You can also log all exceptions on the stack to better understand what went wrong along the line, instead of showing only the last exception, which may not contain a lot of information.

 public function onBootstrap(MvcEvent $e) { $eventManager = $e->getApplication()->getEventManager(); $moduleRouteListener = new ModuleRouteListener(); $moduleRouteListener->attach($eventManager); /** * Log any Uncaught Exceptions, including all Exceptions in the stack */ $sharedManager = $e->getApplication()->getEventManager()->getSharedManager(); $sm = $e->getApplication()->getServiceManager(); $sharedManager->attach('Zend\Mvc\Application', 'dispatch.error', function($e) use ($sm) { if ($e->getParam('exception')){ $ex = $e->getParam('exception'); do { $sm->get('Logger')->crit( sprintf( "%s:%d %s (%d) [%s]\n", $ex->getFile(), $ex->getLine(), $ex->getMessage(), $ex->getCode(), get_class($ex) ) ); } while($ex = $ex->getPrevious()); } } ); } 
+14
source

All Articles