我是否为 Zend-Log 正确配置了错误处理程序和异常管理器?

Am I configuring my error handler and exception manager for Zend-Log correctly?

我有一个 ZF 3 应用程序。我明确记录的消息,例如 $log->debug() 显示得很好。例外情况不会。错误似乎出现了,因为这是转到 stderr 的默认 php 配置。这是来自 modules.config.php 的相关行:

'service_manager' => [
    'factories' => [
        . . . . 
        'log' => \Zend\Log\LoggerServiceFactory::class,

    ],
],
'log' => [
    'writers' => [
        [
            'name' => 'stream',
            'options' => [ 'stream' => 'php://stderr' ]
        ],
    ],
    'errorHandler' => true,
    'exceptionhandler' => true,
],

The lines in the source that lead me to believe this is the correct config.

    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 块中时,记录异常才会起作用。

Sets the default exception handler if an exception is not caught within a try/catch block
Source: 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 块中调度了操作。