visualweber/error-handler-custom

一个用于您的ZF2和ZF3应用程序的错误处理程序,用于捕获PHP错误和异常

1.0 2018-04-23 14:37 UTC

This package is auto-updated.

Last update: 2024-09-12 19:24:44 UTC


README

简介

ErrorHandlerCustom是一个模块,用于错误日志(数据库和邮件)您的ZF2、ZF3 Mvc应用程序,以及ZF Expressive中的异常,在'dispatch.error'或'render.error'或请求和响应期间,以及PHP E_* 错误

特性

  • 使用Db Writer Adapter保存到数据库。
  • 在所有事件处理过程中记录异常(dispatch.error和render.error)和PHP错误。
  • 在配置设置中支持排除PHP E_* 错误(例如:排除E_USER_DEPRECATED)。
  • 在配置设置中支持排除PHP 异常(例如:异常类或扩展它的类)。
  • 在配置的时间范围内,对于相同错误只处理一次日志错误。
  • 如果配置'display_errors' = 0,则为错误设置默认页面(Web访问)或默认消息(控制台访问)。
  • 通过'ajax'配置设置请求是XMLHttpRequest时的默认内容。
  • 提供请求信息(HTTP方法、原始数据、查询数据、文件数据和Cookie数据)。
  • 发送邮件
    • 向列出的配置电子邮件发送多个接收者
    • 在上传错误时将$_FILES包含在附件中。

安装

1. 导入以下SQL语句用于Mysql

DROP TABLE IF EXISTS `log`;

CREATE TABLE `log` (
  `id` bigint(20) UNSIGNED NOT NULL AUTO_INCREMENT,
  `date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  `type` int(11) NOT NULL,
  `event` text NOT NULL,
  `url` varchar(2000) NOT NULL,
  `file` varchar(2000) NOT NULL,
  `line` int(11) NOT NULL,
  `error_type` varchar(255) NOT NULL,
  `trace` text NULL,
  `request_data` text NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=latin1;

如果您使用其他RDBMS,您可以遵循上面的log表结构。

2. 设置您的Zend\Db\Adapter\Adapter服务或您的Doctrine\ORM\EntityManager服务配置

您可以使用'db'(使用Zend\Db)配置或'doctrine'(使用DoctrineORMModule)配置,这些配置将被转换为可用于Zend\Log\Writer\Db

<?php
// config/autoload/local.php
return [
    'db' => [
        'username' => 'mysqluser',
        'password' => 'mysqlpassword',
        'driver'   => 'pdo_mysql',
        'database' => 'mysqldbname',
        'host'     => 'mysqlhost',
        'driver_options' => [
            \PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES \'UTF8\'',
        ],
    ],
];

或者

<?php
// config/autoload/local.php
return [
    'doctrine' => [
        'connection' => [
            'orm_default' => [
                'driverClass' =>'Doctrine\DBAL\Driver\PDOMySql\Driver',
                'params' => [
                    'user'     => 'mysqluser',
                    'password' => 'mysqlpassword',
                    'dbname'   => 'mysqldbname',
                    'host'     => 'mysqlhost',
                    'port'     => '3306',
                    'driverOptions' => [
                        \PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES \'UTF8\'',
                    ],
                ],
            ],
        ],
    ]
];

如果您使用其他RDBMS,您可以配置自己的dbdoctrine配置。

3. 需要此模块使用composer

composer require visualweber/error-handler-custom

4. 复制配置

a. 对于ZF2/ZF3 Mvc应用程序,将error-handler-custom.local.php.dist配置复制到您的本地autoload中并配置它

或者运行复制命令

cp vendor/visualweber/error-handler-custom/config/error-handler-custom.local.php.dist config/autoload/error-handler-custom.local.php

b. 对于ZF Expressive应用程序,将expressive-error-handler-custom.local.php.dist配置复制到您的本地autoload中并配置它

或者运行复制命令

cp vendor/visualweber/error-handler-custom/config/expressive-error-handler-custom.local.php.dist config/autoload/expressive-error-handler-custom.local.php

完成之后,您可以在您的本地配置中修改名为ErrorHandlerCustomLoggererror-handler-custom的logger服务和配置

<?php
// config/autoload/error-handler-custom.local.php or config/autoload/expressive-error-handler-custom.local.php
return [

    'log' => [
        'ErrorHandlerCustomLogger' => [
            'writers' => [

                [
                    'name' => 'db',
                    'options' => [
                        'db'     => 'Zend\Db\Adapter\Adapter',
                        'table'  => 'log',
                        'column' => [
                            'timestamp' => 'date',
                            'priority'  => 'type',
                            'message'   => 'event',
                            'extra'     => [
                                'url'          => 'url',
                                'file'         => 'file',
                                'line'         => 'line',
                                'error_type'   => 'error_type',
                                'trace'        => 'trace',
                                'request_data' => 'request_data'
                            ],
                        ],
                    ],
                ],

            ],
        ],
    ],

    'error-handler-custom' => [
	// it's for the enable/disable the logger functionality
        'enable' => true,

        // default to true, if set to true, then you can see sample:
        // 1. /error-preview page ( ErrorHandlerCustom\Controller\ErrorPreviewController )
        // 2. error-preview command (ErrorHandlerCustom\Controller\ErrorPreviewConsoleController) via
        //       php public/index.php error-preview
        //
        // for zf-expressive ^1.0, the disable error-preview page is by unregister 'error-preview' from this config under "routes",
        // for zf-expressive ^2.0, the disable error-preview page is by unregister 'error-preview' from config/routes
        //
        //
        // otherwise(false), you can't see them, eg: on production env.
        'enable-error-preview-page' => true,

        'display-settings' => [

            // excluded php errors ( https://php.ac.cn/manual/en/errorfunc.constants.php )
            'exclude-php-errors' => [
                \E_USER_DEPRECATED,
            ],

            // excluded exceptions
            'exclude-exceptions' => [
                \App\Exception\MyException::class, // can be an Exception class or class extends Exception class
            ],

            // show or not error
            'display_errors'  => 0,

            // if enable and display_errors = 0, the page will bring layout and view
            'template' => [
                'layout' => 'layout/layout',
                'view'   => 'error-handler-custom/error-default'
            ],

            // if enable and display_errors = 0, the console will bring message
            'console' => [
                'message' => 'We have encountered a problem and we can not fulfill your request. An error report has been generated and sent to the support team and someone will attend to this problem urgently. Please try again later. Thank you for your patience.',
            ],
            // if enable, display_errors = 0, and request XMLHttpRequest
            // on this case, the "template" key will be ignored.
            'ajax' => [
                'message' => <<<json
{
    "type": "http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html",
    "title": "Internal Server Error",
    "status": 500,
    "detail": "We have encountered a problem and we can not fulfill your request. An error report has been generated and sent to the support team and someone will attend to this problem urgently. Please try again later. Thank you for your patience."
}
json
            ],
        ],

        'logging-settings' => [
            // time range for same error, file, line, url, message to be re-logged
	        // in seconds range, 86400 means 1 day
            'same-error-log-time-range' => 86400,
        ],

        'email-notification-settings' => [
            // set to true to activate email notification on log error event
            'enable' => false,

            // Zend\Mail\Message instance registered at service manager
            'mail-message'   => 'YourMailMessageService',

            // Zend\Mail\Transport\TransportInterface instance registered at service manager
            'mail-transport' => 'YourMailTransportService',

            // email sender
            'email-from'    => 'Sender Name <sender@host.com>',

            'email-to-send' => [
                'developer1@foo.com',
                'developer2@foo.com',
            ],
        ],
    ],
    // ...
];

5. 最后,启用它

a. 对于ZF Mvc应用程序

// config/modules.config.php or config/application.config.php
return [
    'Application',
    'ErrorHandlerCustom', // <-- register here
],

b. 对于ZF Expressive应用程序

您需要使用Zend\ServiceManager作为服务容器和Zend\View作为模板引擎。

对于zend-expressive-skeleton ^1.0,它应该已经可以正常工作了!

对于zend-expressive-skeleton ^2.0,您需要打开config/pipeline.php并在默认的ErrorHandler::class注册后添加ErrorHandlerCustom\Middleware\Expressive::class中间件

$app->pipe(ErrorHandler::class);
$app->pipe(ErrorHandlerCustom\Middleware\Expressive::class); // here

并在config/routes.php中添加error-preview路由(可选)

$app->get('/error-preview[/:action]', ErrorHandlerCustom\Middleware\Routed\Preview\ErrorPreviewAction::class, 'error-preview');

以启用错误预览页面。要禁用错误预览页面,只需从路由中删除它。

试试看吧!

Web访问

如果display_errors配置为0,您将看到以下页面

error preview in web

对于生产环境,您可以通过设置['error-handler-custom']['enable-error-preview-page']为false来禁用错误预览示例页面。

控制台访问

如果您使用zend-mvc v3,您需要在您的vendor中包含zendframework/zend-mvc-console,如果没有,您可以通过以下命令安装它:

composer require zendframework/zend-mvc-console --sort-packages

如果display_errors配置为0,您将看到以下页面

error preview in console

对于生产环境,您可以通过设置['error-handler-custom']['enable-error-preview-page']为false来禁用错误预览示例页面。

对于ZF Expressive,没有默认的控制台实现,因此,如果您想在ZF Expressive的控制台中应用它,您可能需要自定义错误处理程序,该程序利用ErrorHandlerCustom\Handler\Logging服务(请参阅ErrorHandlerCustom\Middleware\Expressive类的详细使用说明)。

贡献

我们非常欢迎贡献。请阅读CONTRIBUTING.md