将userid字段添加到zend db logger

时间:2017-09-23 00:39:57

标签: php mysql logging zend-framework zend-framework2

我想将包含用户ID的字段从登录用户添加到zend db logger

这是我目前的代码:

$mapping = array(
        'timestamp' => 'created',
        'priorityName'  => 'type',
        'message'   => 'message'                
);      
$dbAdapter = Pluto::database()->getMasterAdapter();
$writer = new \Zend\Log\Writer\Db($dbAdapter,'logs',$mapping);
$this->logger->addWriter($writer);

我的用户ID列将为userid。如果用户未登录,则应插入0.

不太清楚该怎么做。

更新

这是我当前的处理器:

namespace Pluto\Log;

use Zend\Log\Processor\ProcessorInterface;

class UserAwareProcessor implements ProcessorInterface
{
    /**
     * @param array $event event data
     * @return array event data
     */
    public function process(array $event)
    {
        if (! isset($event['extra'])) {
            $event['extra'] = [];
        }

        $event['extra']['userid'] = 5;

        return $event;
    }   
}

1 个答案:

答案 0 :(得分:0)

您可以使用自定义log processor在写入之前轻松地将任何数据附加/预先添加到日志中。由于在将日志事件传递给编写器之前从记录器调用处理器,因此我将使用以下签名和正文创建MyApp\Log\UserAwareProcessor

<?php
namespace MyApp\Log;

use Zend\Log\Processor\ProcessorInterface

class UserAwareProcessor implements ProcessorInterface
{
    /**
     * @param array $event event data
     * @return array event data
     */
    public function process(array $event)
    {
        if (! isset($event['extra'])) {
            $event['extra'] = [];
        }

        $event['extra']['userId'] = $this->getUserId();

        return $event;
    }

    /**
     * @return int
     */
    private function getUserId()
    {
        // Read the id from session or any other source and return it 
    }
}

最后,在将编写器设置到记录器之后,您还需要将处理器设置为:

$this->logger->addWriter($writer);
$processor = new MyApp\Log\UserAwareProcessor();
$this->logger->addProcessor($processor);

您可能还想结帐log formatters

希望它有所帮助。