How to register a Zend\Log Instance in the ServiceManager in ZF2

11,243

Solution 1

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...');

Solution 2

Alternatively, and more elegantly, you could setup a log listener and keep your logger decoupled from your app. The EventManager is a very powerful component and ZF2 is basically an event driven framework now.

In your module.php you could add something like:

// Setup the Zend Logger, pseudocode
$logger = new Logger;
$writer = new Writer;
$logger->addWriter($writer);

// Attach a logging listener for the log event on application level, working code
$events = StaticEventManager::getInstance();
$events->attach('*', 'log', function($event) use ($logger) {
    $target = get_class($event->getTarget());
    $message = $event->getParam('message', 'No message provided');
    $priority = (int) $event->getParam('priority', Logger::INFO);
    $message = sprintf('%s: %s', $target, $message);
    $logger->log($priority, $message);
});

Then from anywhere, e.g. from a Controller, you can do:

$this->getEventManager()->trigger('log', $this, array(
                                                       'priority' => 7, 
                                                       'message' => 'some log message'
                                                      ));

Solution 3

Maybe use the abstract logger factory for configuration instead of the normal factory

http://framework.zend.com/manual/2.2/en/modules/zend.mvc.services.html#zend-log-loggerabstractservicefactory

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

Solution 4

I created a default database writer object in my bootstrap and registered it in the ServiceManager.

public function onBootstrap(MvcEvent $e)
{
    ...

    $serviceManager     = $e->getApplication()->getServiceManager();
    $dbAdapter          = $serviceManager->get('Zend\Db\Adapter\Adapter');

    $writer = new \Zend\Log\Writer\Db($dbAdapter, 'log_database_table');
    $logger = new \Zend\Log\Logger();
    $logger->addWriter($writer);

    // this is optional but nice to have
    \Zend\Log\Logger::registerErrorHandler($logger);

    $serviceManager->setService('Zend\Log', $logger);
}

The AbstractController is an instance of "ServiceLocatorAwareInterface". So I can just call in my controller

public function indexAction()
{
    ...

    $this->getServiceLocator()->get('Zend\Log')->info('this is a test log message');

    ...
}

Solution 5

Please try it again using the absolute path \

$writer = new \Zend\Log\Writer\Stream('log.log');
$logger = new \Zend\Log\Logger($writer);
Share:
11,243
Al-Punk
Author by

Al-Punk

norm al

Updated on July 09, 2022

Comments

  • Al-Punk
    Al-Punk almost 2 years

    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