如何在Zend Expressive中将PHP错误记录到PHP的错误文件中?

时间:2018-02-08 15:33:18

标签: php logging zend-framework zend-expressive

使用Zend Expressive 2.0.5,我想将PHP错误记录到PHP的错误日志文件中,我经历了https://docs.zendframework.com/zend-expressive/features/error-handling/#handling-exceptions-and-errors

我也看过这篇文章:Zend expressive - php error reporting。这为我清理了很多东西,但仍然没有解决问题。

我做的事情:定义了我自己的ErrorHandlerFactory我将两个听众附加到Zend-stratigility's ErrorHandler

  1. First Listener使用Zend Log登录我的应用程序日志 文件。(只是觉得我的错误会很好 application.log也是。)

  2. 在第二个监听器中,我想登录PHP的错误日志文件,所以我使用了php的error_log()方法。

  3. 问题:

    1. error_log()不按照php的错误处理程序打印日志的方式打印日志。我的意思是:

      当php的错误处理程序打印出错误时,它看起来像这样:

        

      [08-Feb-2018 08:22:51 US / Central] PHP警告:array_push()期望   给出至少2个参数,1   C:\ webserver \ webroot \ myapi \ src \ App \ src \ Action \ PageAction.php on   第38行

      当我使用error_log()打印日志时,它看起来像这样:

        

      [08-Feb-2018 09:03:49 US / Central] array_push()期望至少2   参数,1给出   C:\ webserver \ webroot \ myapi \ src \ App \ src \ Action \ PageAction.php on   第38行

      我在这里缺少的是PHP的错误类型: PHP警告,这是错误代码吗?我得到的错误代码是一个整数,我该如何解析该代码?我应该将错误代码映射到日志中出现的PHP错误常量,例如:警告,通知等,我甚至可以这样做,但问题是:我得到了相同的错误代码 0 php的错误处理程序打印 a WARNING和致命错误日志的时间。

    2. 在PHP的错误日志文件中记录错误是否正确?应该 我做PHP的错误处理程序的工作?错误处理程序可能会执行很多操作,例如:记录错误消息以查找少量错误,但另一个错误消息也记录堆栈跟踪。 如果这不对,那么我怎样才能将错误发送到PHP的error_handler?

      根据我的理解:

        

      我自己的错误处理程序阻止用户查找异常和堆栈   痕迹,而是返回一个       通用消息。这也意味着错误处理程序消耗错误并且不会将其抛到外面,即不会抛出错误   到PHP的错误处理程序。

1 个答案:

答案 0 :(得分:1)

回答问题1:

我能够几乎模拟PHP错误处理程序记录PHP错误的方式。 我做的事情:

  1. 浏览了docsthis SO问题。使用这些我能够将听众附加到Zend-stratigility的ErrorHandler
  2. 通过PHP的Error Constantsset_error_handler(),这给了我一些关于如何找出错误或异常类型的想法。
  3. 下面是我附加侦听器的ErrorHandlerFactory的代码。

    <?php
    // TODO: PHP 7.0.8 is giving strict erros eben if this directive is not enabled. And that too, it should be enabled per file from my understanding.
    //declare(strict_types = 1);
    namespace App\Factories;
    use Interop\Container\ContainerInterface;
    use Psr\Http\Message\RequestInterface;
    use Psr\Http\Message\ResponseInterface;
    use Zend\Log\Logger as ZendLogger;
    use Throwable;
    use Zend\Diactoros\Response;
    use Zend\Expressive\Middleware\ErrorResponseGenerator;
    use Zend\Stratigility\Middleware\ErrorHandler;
    class ErrorHandlerFactory
    {
        /**
         * @param ContainerInterface $container
         * @return ErrorHandler
         * @throws \Psr\Container\ContainerExceptionInterface
         * @throws \Psr\Container\NotFoundExceptionInterface
         */
        public function __invoke(ContainerInterface $container)
        {
            $generator = $container->has(ErrorResponseGenerator::class)
                ? $container->get(ErrorResponseGenerator::class)
                : null;
            $errorHandler = new ErrorHandler(new Response(), $generator);
    
             // attaching a listener for logging into application's log file.
            if ($container->has(ZendLogger::class)) {
                /** @var ZendLogger $logger */
                $logger = $container->get(ZendLogger::class);
                $errorHandler->attachListener(function (
                    Throwable $throwable,
                    RequestInterface $request,
                    ResponseInterface $response
                ) use ($logger) {
                    $logger->err(NULL, [
                        'method'  => $request->getMethod(),
                        'uri'     => (string) $request->getUri(),
                        'message' => $throwable->getMessage(),
                        'file'    => $throwable->getFile(),
                        'line'    => $throwable->getLine(),
                    ]);
                });
            }
    
            // Attaching second listener for logging the errors into the PHP's error log
            $errorHandler->attachListener(function (
                Throwable $throwable,
                RequestInterface $request,
                ResponseInterface $response
            ) {
                // Default Error type, when PHP Error occurs.
                $errorType = sprintf("Fatal error: Uncaught %s", get_class($throwable));
                if (get_class($throwable) === "ErrorException") {
    
                    // this is an Exception
                    /** @noinspection PhpUndefinedMethodInspection */
                    $severity = $throwable->getSeverity();
                    switch($severity) {
                        case E_ERROR:
                        case E_USER_ERROR:
                            $errorType = 'Fatal error';
                            break;
                        case E_USER_WARNING:
                        case E_WARNING:
                            $errorType = 'Warning';
                            break;
                        case E_USER_NOTICE:
                        case E_NOTICE:
                        case E_STRICT:
                            $errorType = 'Notice';
                            break;
                        case E_RECOVERABLE_ERROR:
                            $errorType = 'Catchable fatal error';
                            break;
                        case E_USER_DEPRECATED:
                        case E_DEPRECATED:
                            $errorType = "Deprecated";
                            break;
                        default:
                            $errorType = 'Unknown error';
                    }
    
                    error_log(sprintf("PHP %s: %s in %s on line %d", $errorType, $throwable->getMessage(), $throwable->getFile(), $throwable->getLine()), 0);
                }
                else {
                    // this is an Error.
                    error_log(sprintf("PHP %s: %s in %s on line %d \nStack trace:\n%s", $errorType, $throwable->getMessage(), $throwable->getFile(), $throwable->getLine(), $throwable->getTraceAsString()), 0);
                }
            });
    
            return $errorHandler;
        }
    }
    

    除此之外,还需要将此Factory添加到依赖项中。 在文件中: dependencies.global.php数组中的factories

    替换

    Zend\Stratigility\Middleware\ErrorHandler::class => Container\ErrorHandlerFactory::class,

    Zend\Stratigility\Middleware\ErrorHandler::class => \App\Factories\ErrorHandlerFactory::class
    

    这应该几乎模拟了php错误处理程序的日志记录行为。

    回答问题2:

    我认为这样做很好,因为PHP本身提供了set_error_handler(),无论如何我们必须自己处理错误而不是将它传递给PHP的错误处理程序。如果我们的ErrorHandler(侦听器)可以复制消息并使用error_log()登录到PHP的错误日志中,那么就可以了。