Can't get Logger service in ZF2

2019-07-28 11:02发布

问题:

I struggled the problem for days, but still don't find what's wrong with it.

Here is my configuration segment in 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'
                )
            )
        )
    )
)

and I try to get the service instance in my controller:

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

and exception thrown:

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

updated Thank you for your help ocramius

I move the segment to module.config.php, and it thrown exception this time:

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:

As discussed on IRC, the problems here were 2:

  • the file where you had this configuration was config/application.config.php (which is not the module/merged configuration, but what gets put into service "ApplicationConfig")
  • the abstract factory couldn't instantiate a service due to an exception. In order to debug the exception, you can do something like following:
try {
    // ...
    $logger = $this->getServiceLocator()->get('Log\\App');
    // ...
} catch (\Exception $e) {
    do {
        var_dump($e->getMessage());
    } while ($e = $e->getPrevious());
}

Most probably, your configuration has a wrong path for the file that has to be accessed by the log writer, and that will come up by tracing these exceptions like I've just shown.