zend 2日志出现问题



我目前正在使用zend 2记录器。我有一个error_log表,其中包含以下字段:

  • 错误_log_id
  • 消息
  • 时间戳
  • 优先级名称
  • 优先级
  • ip
  • user_id

下面是我的代码

$db         = $this->service->get('ZendDbAdapterAdapter');
$uId        = 0;
if ($auth->hasIdentity()) {
    $oId        = $auth->getIdentity();
    $uId        = $oId->user_id;
}
$mapping = array(
    'timestamp'     => 'timestamp',
    'priority'      => 'priority',
    'priorityName'  => 'priorityName',
    'message'       => 'message',
);
$writer = new ZendLogWriterDb($db, 'error_log_table', $mapping);
$logger = new ZendLogLogger();
$logger->addWriter($writer);
$logger->info('Informational message');

此操作正常,并且将更新以下字段。时间戳,优先级,优先级名称,&消息

我还想更新user_id和ip字段。我该怎么做?(在zend 1中,我们可以使用setEventItem()函数来实现这一点)。我必须调用什么函数才能在zend2日志中添加额外的参数?

有人帮忙吗?

您可以将$logger->info()与第二个参数"extra"一起使用。这应该是一个Traversal,例如一个数组。

请尝试以下内容。

$logger->info('message', array('user_id' => $uId, 'ip' => $_SERVER['REMOTE_ADDR']));

我想您必须添加一个额外的数据库列"extra",其中存储了额外的日志事件数据。

简单地说:声明自己的记录器与AuthenticationService有依赖关系,覆盖log方法,使用$extra变量存储附加数据

详细信息:

Application\Log\LoggerFactory.php

class LoggerFactory implements FactoryInterface
{
    protected $mapping = array(
        // Your mapping here
    );
    public function createService(ServiceLocatorInterface $serviceLocator)
    {
        $authenticationService = $serviceLocator->get('ZendAuthenticationAuthenticationService');
        $dbAdapter = $serviceLocator->get('ZendDbAdapterStatisticAdapter');
        $writer = new DbWriter($dbAdapter, 'error_log_table', $this->mapping);
        $logger = new Logger();
        $logger->addWriter($writer);
        $logger->setAuthenticationService($authenticationService);
        return $logger;
    }
}

Application\Log\Logger.php

class Logger extends ZendLogLogger
{
    protected $authenticationService;
    public function setAuthenticationService($authenticationService)
    {
         $this->authenticationService = $authenticationService;
    }
    public function log($priority, $message, $extra = array())
    {
        $remoteAddress = new RemoteAddress;
        $ip = $remoteAddress->setUseProxy(true)->getIpAddress();   
        $userId = null;
        if ($this->authenticationService->hasIdentity()) {
             $userId = $this->authenticationService->getIdentity()->getId();
        } 
        $extra = array_merge($extra, array(
            'ip' => ip2long($ip),
            'user_id' => $userId
        ));
        return parent::log($priority, $message, $extra);
    }

module.config.php

'service_manager' => array(
    'factories' => array(
        'ZendLog' => 'ApplicationLogLoggerFactory',
    ),

您的控制器

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

相关内容

  • 没有找到相关文章

最新更新