无法在ZF2中获得Logger服务

时间:2014-03-28 17:27:34

标签: php logging zend-framework2

我挣扎了几天这个问题,但仍然没有发现它的问题。

这是application.config.php中的配置段:

// Initial configuration with which to seed the ServiceManager.
// Should be compatible with Zend\ServiceManager\Config.
'service_manager' => array(
    'abstract_factories' => array(
        'Zend\Log\LoggerAbstractServiceFactory',
        'Zend\Cache\Service\StorageCacheAbstractServiceFactory',
    )
),

'log' => array(
    'Log\App' => array(
        'writers' => array(
            array(
                'name' => 'stream',
                'priority' => 1000,
                'options' => array(
                    'stream' => 'data/logs/app.log'
                )
            )
        )
    )
)

我尝试在我的控制器中获取服务实例:

$logger = $this->getServiceLocator()->get('Log\\App');

抛出异常:

An error occurred
An error occurred during execution; please try again later.
Additional information:
Zend\ServiceManager\Exception\ServiceNotFoundException
File:
/var/openresty/html/skeleton-zf2/vendor/zendframework/zendframework/library/Zend/ServiceManager/ServiceManager.php:529
Message:
Zend\ServiceManager\ServiceManager::get was unable to fetch or create an instance for Log\App

更新 感谢您的帮助 ocramius

我将段移动到module.config.php,这次抛出异常:

Zend\ServiceManager\Exception\ServiceNotCreatedException
File:
/var/openresty/html/skeleton-zf2/vendor/zendframework/zendframework/library/Zend/ServiceManager/ServiceManager.php:1070
Message:
An abstract factory could not create an instance of applicationweb(alias: Application\Web).

1 个答案:

答案 0 :(得分:2)

正如在IRC上所讨论的,这里的问题是2:

  • 您拥有此配置的文件是config/application.config.php不是模块/合并配置,但是投入使用的内容"ApplicationConfig"
  • 由于异常,抽象工厂无法实例化服务。为了调试异常,您可以执行以下操作:
try {
    // ...
    $logger = $this->getServiceLocator()->get('Log\\App');
    // ...
} catch (\Exception $e) {
    do {
        var_dump($e->getMessage());
    } while ($e = $e->getPrevious());
}

最有可能的情况是,您的配置对于必须由日志编写者访问的文件有一个错误的路径,并且会通过跟踪这些异常来实现,就像我刚刚显示的那样。