我有 ZF 3 应用程序。我明确记录的消息,例如
$log->debug()
显示得很好。例外则不然。似乎会出现错误,因为这是转到 stderr 的默认 php 配置。以下是 module.config.php 中的相关行:
'service_manager' => [
'factories' => [
. . . .
'log' => \Zend\Log\LoggerServiceFactory::class,
],
],
'log' => [
'writers' => [
[
'name' => 'stream',
'options' => [ 'stream' => 'php://stderr' ]
],
],
'errorHandler' => true,
'exceptionhandler' => true,
],
if (isset($options['exceptionhandler']) && $options['exceptionhandler'] === true) {
static::registerExceptionHandler($this);
}
if (isset($options['errorhandler']) && $options['errorhandler'] === true) {
static::registerErrorHandler($this);
}
为了测试它,我做了以下端点:
public function errorAction()
{
$msg = $this->params()->fromQuery('msg', 'Default Error message');
trigger_error('Index Error Action' . $msg, E_USER_ERROR);
$model = new JsonErrorModel(['msg' => $msg]);
return $model;
}
public function exceptionAction()
{
$msg = $this->params()->fromQuery('msg', 'Default Error message');
throw new \RuntimeException('Index Exception Action' . $msg);
$model = new JsonErrorModel(['msg' => $msg]);
return $model;
}
您的配置数组中有拼写错误
'log' => [
....
'errorHandler' => true,
....
],
这个索引不应该是驼峰命名法,而应该是
errorhandler
(所有字母都是小写)。我还会将 fatal_error_shutdownfunction => true
添加到配置中,以便您记录致命错误。
Zend 使用
set_exception_handler
来处理异常,因此请记住,只有当异常不在 try/catch 块中时,日志记录才会起作用。
如果在 try/catch 块中未捕获异常,则设置默认异常处理程序
来源: http://php.net/manual/en/function.set-exception-handler.php
所有这些功能都可以手动设置:
\Zend\Log\Logger::registerErrorHandler($logger);
\Zend\Log\Logger::registerFatalErrorShutdownFunction($logger);
\Zend\Log\Logger::registerExceptionHandler($logger);
如果您想测试它,您可以执行以下操作:
错误
public function errorAction()
{
$log = $this->getServiceLocator()->get('log'); // init logger. You shouldn't use getServiceLocator() in controller. Recommended way is injecting through factory
array_merge([], 111);
}
它应该写在日志中:
2017-03-09T15:33:47+01:00 WARN (4): array_merge(): Argument #2 is not an array {"errno":2,"file":"[...]\\module\\Application\\src\\Application\\Controller\\IndexController.php","line":80}
致命错误
public function fatalErrorAction()
{
$log = $this->getServiceLocator()->get('log'); // init logger. You shouldn't use getServiceLocator() in controller. Recommended way is injecting through factory
$class = new ClassWhichDoesNotExist();
}
日志:
2017-03-09T15:43:06+01:00 ERR (3): Class 'Application\Controller\ClassWhichDoesNotExist' not found {"file":"[...]\\module\\Application\\src\\Application\\Controller\\IndexController.php","line":85}
或者如果您需要全局记录器,您可以在
Module.php
文件中初始化记录器。
我认为不可能在控制器的操作中记录异常。我不确定,但操作是在 try/catch 块中调度的。