您可以附加到调度错误事件:
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'));
}
}
);
}
一个简单记录器的示例服务配置
'factories' => array(
'Logger' => function($sm){
$logger = new \Zend\Log\Logger;
$writer = new \Zend\Log\Writer\Stream('./data/log/'.date('Y-m-d').'-error.log');
$logger->addWriter($writer);
return $logger;
},
// ...
);
您还可以记录堆栈中的所有异常,以更好地了解发生了什么问题,而不是只显示最后一个异常,这可能不包含太多信息。
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());
}
}
);
}