Reputation: 234
how to configure and use logger in ZEND-framework 2 ? is it good way to create logger object in application bootstrap ?
Upvotes: 1
Views: 1409
Reputation: 354
Since Zend Framework 2.2, just set these lines in your config:
'log' => array(
'Application\Log' => array(
'writers' => array(
array(
'name' => 'stream',
'priority' => 1000,
'options' => array(
'stream' => 'data/logs/app.log',
),
),
),
),
),
Use it in your application controller:
protected $log;
public function getLog()
{
if (!$this->log) {
$sm = $this->getServiceLocator();
$this->log = $sm->get('Application\Log');
}
return $this->log;
}
Read more - zf2.2 release notes
Upvotes: 0
Reputation: 12809
First you can setup your Service Manager Config:
'factories' => array(
'Zend\Log\Logger' => function($sm){
$logger = new \Zend\Log\Logger;
$writer = new \Zend\Log\Writer\Stream('./data/log/'.date('Y-m-d').'-error.log');
$logger->addWriter($writer);
return $logger;
},
)
then in your controller you can add something like this
/**
* Get the logger
*
* @return \Zend\Log\Logger
*/
protected function _getLog()
{
if($this->_log == NULL) {
$this->_log = $this->getServiceLocator()->get('Zend\Log\Logger');
}
return $this->_log;
}
/**
* Shortcut for logging method.
* Swapped parameter order to save code inside controllers.
*
* @param mixed $message
* @param int $priority
* @param array|Traversable $extra
* @return Logger
* @throws Exception\InvalidArgumentException if message can't be cast to string
* @throws Exception\InvalidArgumentException if extra can't be iterated over
* @throws Exception\RuntimeException if no log writer specified
*/
protected function _log($message, $priority = \Zend\Log\Logger::DEBUG, $extra = array())
{
return $this->_getLog()->log($priority, $message, $extra);
}
Notice the order of the parameters was swapped, just to cut down on code in the controller, makes things a little simpler.
Then you have a shortcut if you want to log anything in your controller:
public function testAction()
{
$this->_log('Testing');
}
Upvotes: 2
Reputation: 1370
You should take a look at Rob Allen's blog on logging exceptions. He shows how to use a ServiceManager
factory in one module to instantiate the logger and writers. You can then call the logger through the ServiceManager
from any other class that has access to it, such as controllers.
Upvotes: 1