zend 2 日志问题

Issue with zend 2 log

我目前正在使用 zend 2 记录器。我有一个包含以下字段的 table error_log

下面是我的代码

$db         = $this->service->get('Zend\Db\Adapter\Adapter');
$uId        = 0;

if ($auth->hasIdentity()) {
    $oId        = $auth->getIdentity();
    $uId        = $oId->user_id;
}

$mapping = array(
    'timestamp'     => 'timestamp',
    'priority'      => 'priority',
    'priorityName'  => 'priorityName',
    'message'       => 'message',
);
$writer = new \Zend\Log\Writer\Db($db, 'error_log_table', $mapping);
$logger = new \Zend\Log\Logger();
$logger->addWriter($writer);

$logger->info('Informational message');

这工作正常,将更新以下字段。时间戳、优先级、优先级名称和消息。

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

有人帮忙吗?

简要说明:声明自己的记录器依赖于 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('Zend\Authentication\AuthenticationService');

        $dbAdapter = $serviceLocator->get('Zend\Db\Adapter\StatisticAdapter');
        $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 \Zend\Log\Logger
{

    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(
        'Zend\Log' => 'Application\Log\LoggerFactory',
    ),

您的控制器

$this->getServiceLocator()->get('Zend\Log')->info('Info');

您可以使用带有第二个参数的 $logger->info() "extra"。这应该是一个遍历,例如数组。

试试下面的方法。

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

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