我目前正在使用zend 2记录器。我有一个表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 log中添加额外的参数?
有人请帮忙吗?
答案 0 :(得分:0)
简要说明:使用AuthenticationService
声明自己的记录器,覆盖log
方法,使用$extra
变量存储其他数据
详细说明:
<强>应用\ 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;
}
}
<强>应用\ 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');
答案 1 :(得分:0)
你可以使用$ logger-&gt; info()和第二个参数&#34; extra&#34;。这应该是一个遍历,例如数组。
试试以下内容。
$logger->info('message', array('user_id' => $uId, 'ip' => $_SERVER['REMOTE_ADDR']));
我猜你必须添加一个额外的数据库列&#34; extra&#34;,其中存储了额外的日志记录事件数据。