logging - 如何在 Apigility ZF2 应用程序中捕获和记录所有异常?

标签 logging exception-handling zend-framework2 laminas-api-tools exception-logging

我想在 Apigility Zend Framework 2 应用程序中构建错误处理和日志记录机制,并捕获和记录所有异常。

经过一番研究,我发现了一个堆栈溢出 answer有了一个解决方案,这似乎正好满足了这个要求。这是答案中的代码(有一些小的命名和格式修改):

Module.php

...

use Zend\Mvc\ModuleRouteListener;
use Zend\Log\Logger;
use Zend\Log\Writer\Stream;

...

class Module implements ApigilityProviderInterface
{

    public function onBootstrap(MvcEvent $mvcEvent)
    {
        $eventManager = $mvcEvent->getApplication()->getEventManager();
        $moduleRouteListener = new ModuleRouteListener();
        $moduleRouteListener->attach($eventManager);
        /**
         * Log any Uncaught Exceptions, including all Exceptions in the stack
         */
        $sharedEventManager = $mvcEvent->getApplication()->getEventManager()->getSharedManager();
        $serviceManager = $mvcEvent->getApplication()->getServiceManager();
        $sharedEventManager->attach('Zend\Mvc\Application', MvcEvent::EVENT_DISPATCH_ERROR,
            function($mvcEvent) use ($serviceManager) {
                if ($mvcEvent->getParam('exception')){
                    $exception = $mvcEvent->getParam('exception');
                    do {
                        $serviceManager->get('Logger')->crit(
                            sprintf(
                               "%s:%d %s (%d) [%s]\n", 
                                $exception->getFile(), 
                                $exception->getLine(), 
                                $exception->getMessage(), 
                                $exception->getCode(), 
                                get_class($exception)
                            )
                        );
                    }
                    while($exception = $exception->getPrevious());
                }
            }
        );
    }

    ...

    public function getServiceConfig() {
        return array(
            'factories' => array(
                // V1
                ...
                'Logger' => function($sm){
                    $logger = new Logger;
                    $writer = new Stream('/var/log/httpd/sandbox-log');
                    $logger->addWriter($writer);
                    return $logger;
                },
            ),
            ...
        );
    }

}

所以现在我已经在代码中的几个地方(在 throw new \Exception('foo') ,在 Resource 和在 Service 类中)尝试了这个(使用简单的 Mapper )并希望得到缓存的异常并登录到我定义的文件。但它不起作用。

难道我做错了什么?什么?如何让它工作? 如何在 Apigility 驱动的 Zend Framework 2 应用程序中捕获和记录所有异常?

附加信息:代码中一个地方的例子,在那里抛出异常:
class AddressResource extends AbstractResourceListener ...
{
    public function fetch($id) {
        throw new \Exception('fetch_EXCEPTION');
        $service = $this->getAddressService();
        $entity = $service->getAddress($id);
        return $entity;
    }
}

附加信息:响应中的跟踪(如果在 throw new \Exception('fetch_EXCEPTION'); 中设置 BarResource#fetch(...) 时):
{
    "trace": [
        {
            "file": "/var/www/my-project/vendor/zfcampus/zf-rest/src/AbstractResourceListener.php",
            "line": 166,
            "function": "fetch",
            "class": "FooAPI\\V1\\Rest\\Bar\\BarResource",
            "type": "->",
            "args": [
                "1"
            ]
        },
        {
            "function": "dispatch",
            "class": "ZF\\Rest\\AbstractResourceListener",
            "type": "->",
            "args": [
                {}
            ]
        },
        {
            "file": "/var/www/my-project/vendor/zendframework/zendframework/library/Zend/EventManager/EventManager.php",
            "line": 444,
            "function": "call_user_func",
            "args": [
                [
                    {},
                    "dispatch"
                ],
                {}
            ]
        },
        {
            "file": "/var/www/my-project/vendor/zendframework/zendframework/library/Zend/EventManager/EventManager.php",
            "line": 205,
            "function": "triggerListeners",
            "class": "Zend\\EventManager\\EventManager",
            "type": "->",
            "args": [
                "fetch",
                {},
                {}
            ]
        },
        {
            "file": "/var/www/my-project/vendor/zfcampus/zf-rest/src/Resource.php",
            "line": 541,
            "function": "trigger",
            "class": "Zend\\EventManager\\EventManager",
            "type": "->",
            "args": [
                {},
                {}
            ]
        },
        {
            "file": "/var/www/my-project/vendor/zfcampus/zf-rest/src/RestController.php",
            "line": 483,
            "function": "fetch",
            "class": "ZF\\Rest\\Resource",
            "type": "->",
            "args": [
                "1"
            ]
        },
        {
            "file": "/var/www/my-project/vendor/zendframework/zendframework/library/Zend/Mvc/Controller/AbstractRestfulController.php",
            "line": 366,
            "function": "get",
            "class": "ZF\\Rest\\RestController",
            "type": "->",
            "args": [
                "1"
            ]
        },
        {
            "file": "/var/www/my-project/vendor/zfcampus/zf-rest/src/RestController.php",
            "line": 332,
            "function": "onDispatch",
            "class": "Zend\\Mvc\\Controller\\AbstractRestfulController",
            "type": "->",
            "args": [
                {}
            ]
        },
        {
            "function": "onDispatch",
            "class": "ZF\\Rest\\RestController",
            "type": "->",
            "args": [
                {}
            ]
        },
        {
            "file": "/var/www/my-project/vendor/zendframework/zendframework/library/Zend/EventManager/EventManager.php",
            "line": 444,
            "function": "call_user_func",
            "args": [
                [
                    {},
                    "onDispatch"
                ],
                {}
            ]
        },
        {
            "file": "/var/www/my-project/vendor/zendframework/zendframework/library/Zend/EventManager/EventManager.php",
            "line": 205,
            "function": "triggerListeners",
            "class": "Zend\\EventManager\\EventManager",
            "type": "->",
            "args": [
                "dispatch",
                {},
                {}
            ]
        },
        {
            "file": "/var/www/my-project/vendor/zendframework/zendframework/library/Zend/Mvc/Controller/AbstractController.php",
            "line": 118,
            "function": "trigger",
            "class": "Zend\\EventManager\\EventManager",
            "type": "->",
            "args": [
                "dispatch",
                {},
                {}
            ]
        },
        {
            "file": "/var/www/my-project/vendor/zendframework/zendframework/library/Zend/Mvc/Controller/AbstractRestfulController.php",
            "line": 300,
            "function": "dispatch",
            "class": "Zend\\Mvc\\Controller\\AbstractController",
            "type": "->",
            "args": [
                {},
                {}
            ]
        },
        {
            "file": "/var/www/my-project/vendor/zendframework/zendframework/library/Zend/Mvc/DispatchListener.php",
            "line": 93,
            "function": "dispatch",
            "class": "Zend\\Mvc\\Controller\\AbstractRestfulController",
            "type": "->",
            "args": [
                {},
                {}
            ]
        },
        {
            "function": "onDispatch",
            "class": "Zend\\Mvc\\DispatchListener",
            "type": "->",
            "args": [
                {}
            ]
        },
        {
            "file": "/var/www/my-project/vendor/zendframework/zendframework/library/Zend/EventManager/EventManager.php",
            "line": 444,
            "function": "call_user_func",
            "args": [
                [
                    {},
                    "onDispatch"
                ],
                {}
            ]
        },
        {
            "file": "/var/www/my-project/vendor/zendframework/zendframework/library/Zend/EventManager/EventManager.php",
            "line": 205,
            "function": "triggerListeners",
            "class": "Zend\\EventManager\\EventManager",
            "type": "->",
            "args": [
                "dispatch",
                {},
                {}
            ]
        },
        {
            "file": "/var/www/my-project/vendor/zendframework/zendframework/library/Zend/Mvc/Application.php",
            "line": 314,
            "function": "trigger",
            "class": "Zend\\EventManager\\EventManager",
            "type": "->",
            "args": [
                "dispatch",
                {},
                {}
            ]
        },
        {
            "file": "/var/www/my-project/public/index.php",
            "line": 56,
            "function": "run",
            "class": "Zend\\Mvc\\Application",
            "type": "->",
            "args": []
        }
    ],
    "type": "http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html",
    "title": "Internal Server Error",
    "status": 500,
    "detail": "fetch_EXCEPTION"
}

最佳答案

我们目前正在成功使用以下代码来捕获来自 Apigility 的所有错误响应:

$app = $event->getTarget();
$em = $app->getEventManager();

$sendResponseListener = $app->getServiceManager()->get('SendResponseListener');
$sendResponseListener->getEventManager()->attach(SendResponseEvent::EVENT_SEND_RESPONSE,  function(SendResponseEvent $event) {
    $response = $event->getResponse();
    if ($response instanceof ApiProblemResponse) {
          $error = $response->getApiProblem()->toArray();
          // inspect $error array and log the information you want
    }
});

关于logging - 如何在 Apigility ZF2 应用程序中捕获和记录所有异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30720112/

相关文章:

c++ - 当我 `throw` 某事时,它存储在内存中的什么位置?

php - Zend 2 错误 : Uncaught exception 'Zend\Stdlib\Exception\InvalidArgumentException'

php - 在 MVC 架构中记录数据库错误的位置

gnome - gnome vino-server 的日志在哪里?

python - 需要一种更好的方法来从 python 执行控制台命令并记录结果

events - 使用 truffle 测试以太坊事件日志

exception - 如何捕获使用 Async.AwaitTask 运行的任务抛出的异常

exception-handling - 如何在 lua 解释器中正确调用异常

php - 想要在ZF2中使用一种形式插入两个表

python - 在Jinja扩展程序中进行优美的错误处理和日志记录