I am wondering what is the best way to initiate and re-use a logger instance through the ServiceManager in ZF2. Of course I can do a simple method to be used in any class, like:
public function getLogger () {
$this->logger = new Logger();
$this->logger->addWriter(new Writer\Stream('/log/cms_errors.log'));
return $logger;
}
but I was wondering what is the best way to register a similar structure in the global.php. So far I can
add the following to global.php
'Zend\Log'=>array(
'timestampFormat' => 'Y-m-d',
array(
'writerName' => 'Stream',
'writerParams' => array(
'stream' => '/log/zend.log',
),
'formatterName' => 'Simple',
),
),
If I try invoking it through:
$this->getServiceLocator()->get('Zend\Log')
I get a :
Zend\ServiceManager\ServiceManager::get was unable to fetch or create an instance for Zend\Log
Add the following data to 'global.php'
'service_manager' => array(
'factories' => array(
'Zend\Log' => function ($sm) {
$log = new Zend\Log\Logger();
$writer = new Zend\Log\Writer\Stream('./data/logs/logfile');
$log->addWriter($writer);
return $log;
},
),
),
And then you'll be able to call
$this->getServiceLocator()->get('Zend\Log')->info('Something...');