我目前正在使用 zend 2 logger。我有一个表
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 日志中添加额外参数?
有人帮忙吗?
您可以将 $logger->info() 与第二个参数“extra”一起使用。这应该是一个遍历,例如数组。
尝试以下方法。
$logger->info('message', array('user_id' => $uId, 'ip' => $_SERVER['REMOTE_ADDR']));
我想你必须添加一个额外的数据库列“extra”,其中存储额外的日志记录事件数据。
简单地说:声明自己的记录器,并依赖于
AuthenticationService
,重写log
方法,使用$extra
变量来存储附加数据
详细:
应用程序\日志\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;
}
}
应用程序\日志\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');