如何在ZF2中的ServiceManager中注册ZendLog实例



我想知道通过ZF2中的ServiceManager启动和重用记录器实例的最佳方式是什么。当然,我可以做一个简单的方法在任何类中使用,比如:

public function getLogger () {
        $this->logger = new Logger();
        $this->logger->addWriter(new WriterStream('/log/cms_errors.log'));
        return $logger;
    }

但我想知道在global.php中注册类似结构的最佳方式是什么。到目前为止,我可以

将以下内容添加到global.php

'ZendLog'=>array(
        'timestampFormat' => 'Y-m-d',
        array(
            'writerName'   => 'Stream',
            'writerParams' => array(
                'stream'   => '/log/zend.log',
            ),
            'formatterName' => 'Simple',            
        ),
    ),

如果我尝试通过调用它

$this->getServiceLocator()->get('ZendLog')

我得到一个:

ZendServiceManagerServiceManager::get was unable to fetch or create an instance for ZendLog

将以下数据添加到"global.php"

'service_manager' => array(
    'factories' => array(
        'ZendLog' => function ($sm) {
            $log = new ZendLogLogger();
            $writer = new ZendLogWriterStream('./data/logs/logfile');
            $log->addWriter($writer);
            return $log;
        },
    ),
),

然后你就可以打电话给

$this->getServiceLocator()->get('ZendLog')->info('Something...');

或者,更优雅的是,您可以设置一个日志侦听器,并使记录器与应用程序解耦。EventManager是一个非常强大的组件,ZF2现在基本上是一个事件驱动的框架。

在您的module.php中,您可以添加以下内容:

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

然后从任何地方,例如从控制器,你可以做:

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

也许使用抽象记录器工厂进行配置,而不是使用正常的工厂

http://framework.zend.com/manual/2.2/en/modules/zend.mvc.services.html#zend-日志记录器抽象服务工厂

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

请使用绝对路径\重试

$writer = new ZendLogWriterStream('log.log');
$logger = new ZendLogLogger($writer);

我在引导程序中创建了一个默认的数据库编写器对象,并将其注册到ServiceManager中。

public function onBootstrap(MvcEvent $e)
{
    ...
    $serviceManager     = $e->getApplication()->getServiceManager();
    $dbAdapter          = $serviceManager->get('ZendDbAdapterAdapter');
    $writer = new ZendLogWriterDb($dbAdapter, 'log_database_table');
    $logger = new ZendLogLogger();
    $logger->addWriter($writer);
    // this is optional but nice to have
    ZendLogLogger::registerErrorHandler($logger);
    $serviceManager->setService('ZendLog', $logger);
}

AbstractController是"ServiceLocatorAwareInterface"的一个实例。所以我可以打电话给我的控制器

public function indexAction()
{
    ...
    $this->getServiceLocator()->get('ZendLog')->info('this is a test log message');
    ...
}

相关内容

  • 没有找到相关文章

最新更新