How to use the Zend_Log instance that was created using the Zend_Application_Resource_Log in a model class

loggingzend-framework

Our Zend_Log is initialized by only adding the following lines to application.ini

resources.log.stream.writerName = "Stream"
resources.log.stream.writerParams.mode = "a"

So Zend_Application_Resource_Log will create the instance for us.

We are already able to access this instance in controllers via the following:

public function getLog()
{
    $bootstrap = $this->getInvokeArg('bootstrap');

    //if (is_null($bootstrap)) return false;

    if (!$bootstrap->hasPluginResource('Log')) {
        return false;
    }
    $log = $bootstrap->getResource('Log');
    return $log;
}   

So far, so good.

Now we want to use the same log instance in model classes, where we can not access the bootstrap.

Our first idea was to register the very same Log instance in Zend_Registry to be able to use Zend_Registry::get('Zend_Log') everywhere we want:

in our Bootstrap class:

protected function _initLog() {      
    if (!$this->hasPluginResource('Log')) {
        throw new Zend_Exception('Log not enabled');
    }

$log = $this->getResource('Log');

    assert( $log != null);

    Zend_Registry::set('Zend_Log', $log);
}

Unfortunately this assertion fails ==> $log IS NULL — but why??

It is clear that we could just initialize the Zend_Log manually during bootstrapping without using the automatism of Zend_Application_Resource_Log, so this kind of answers will not be accepted.

Best Answer

This is the final solution. We basically shall not call the function _initLog()

Big thanks to ArneRie!

// Do not call this function _initLog() ! 
protected function _initRegisterLogger() {
    $this->bootstrap('Log');

    if (!$this->hasPluginResource('Log')) {
        throw new Zend_Exception('Log not enabled in config.ini');
    }

    $logger = $this->getResource('Log');
    assert($logger != null);
    Zend_Registry::set('Zend_Log', $logger);
}
Related Topic