views:

100

answers:

3

Is there a better way to have a globally accessible Zend_Log object?

In Bootstrap.php I'm doing:

protected function _initLogging()
{
    $logger = new Zend_Log();
    $writer = new Zend_Log_Writer_Stream(APPLICATION_PATH . '/../app.log');
    $logger->addWriter($writer);
    Zend_Registry::set('log', $logger);
}

Then throughout the application I'll use:

Zend_Registry::get('log')->debug('hello world');

It's not horrible I guess. It just seems kind of verbose.

+1  A: 

well you could wrap it in a 'manager class':

class My_Log_Manager
{
  static $_instance = null;
  protected $_logInstance = null;

  public static function getInstance(){}
  public function getLogInstance(){}
  public static function log($level, $msg)
  {
     self::getInstance()->_logInstance->$level($msg);
  }
}

you could then set up the static methods however you want either with something like catchall example, or by implementing __call or whatever. then you could jsut call the static methods on that class like My_Log_Manager::<methodName>().

prodigitalson
+5  A: 

Quoting from this newsgroup entry:

class My_Helper_Logger extends Zend_Controller_Action_Helper_Abstract
{
  function init()
  {
    $this->getActionController()->logger = $this->getActionController()
                                                  ->getInvokeArg('bootstrap')
                                                    ->getResource('logger');
  }
}

to apply the helper all you have to do is to put in the init() function of Michael's example this line:

Zend_Controller_Action_HelperBroker::addHelper(new My_Helper_Logger());

and in every action of your controllers now you can access the logger as $this->logger

There is a number of other suggestions, so check the link.

Gordon
+1 for a solution allowing controller access to `$this->logger`.
cballou
After reading some of the newsgroup one of the downsides to this method is you are not able to log inside models, view helpers and/or resource plugins
cballou
You could inject it into the View or Model from the Controller though.
Gordon
+1  A: 

You could try skipping addWriter() to remove a single line:

$writer = new Zend_Log_Writer_Stream(APPLICATION_PATH . '/../app.log');  
$logger = new Zend_Log($writer);  
Zend_Registry::set('log', $logger);
cballou