繁体   English   中英

如何使用在模型类中使用Zend_Application_Resource_Log创建的Zend_Log实例

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

通过仅将以下行添加到application.ini来初始化我们的Zend_Log

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

因此Zend_Application_Resource_Log将为我们创建实例。

我们已经可以通过以下方式在控制器中访问此实例:

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;
}   

到现在为止还挺好。

现在,我们要在无法访问引导程序的模型类中使用相同的日志实例。

我们的第一个想法是在Zend_Registry中注册相同的Log实例,以便能够在我们想要的任何地方使用Zend_Registry :: get('Zend_Log'):

在我们的Bootstrap类中:

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);
}

不幸的是,该断言失败==> $ log IS NULL ---但是为什么?

显然,我们可以在引导过程中手动初始化Zend_Log,而无需使用Zend_Application_Resource_Log的自动功能,因此这种答案将不被接受。

这是最终的解决方案。 我们基本上不会调用函数_initLog()

非常感谢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);
}

可能此时未引导,请尝试:

    try {
            $this->bootstrap('log'); // bootstrap log
            $logger = $this->getResource('log');
        } catch (Zend_Application_Bootstrap_Exception $e) {
            $logger = new Zend_Log();
            $writer = new Zend_Log_Writer_Null();
            $logger->addWriter($writer);
        }
        $registry = Zend_Registry::set('logger', $logger);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM