如何制作自定义日志(使用Zend2)并为每个日志事件设置用户名。 以下是我尝试的例子:
public function log( )
{
$log_file = 'path/to/logfile.log';
$format = '%timestamp% %priorityName% (%username%) %message%';
$formatter = new Zend\Log\Formatter\Simple($format);
$formatter->setDateTimeFormat('H:i:s');
$formatter->format( array('username'=> SET_USER_NAME ));
$logWriter = new LogWriter($log_file);
$logWriter->setFormatter($formatter);
$logger = new Logger;
$logger->addWriter( $logWriter );
return $logger;
}
我尝试了以下
$this->log()->info(" Log message " );
结果是:
11:33:54 INFO (%username%) Log message
谢谢!
答案 0 :(得分:0)
您可以使用third parameter of log method extra
- 额外数据数组,这些数据将转换为json并由格式化程序自动添加到日志消息中(Zend\Log\Formatter\Simple::format)
简单示例:
$writer = new \Zend\Log\Writer\Stream('php://output');
$logger = new \Zend\Log\Logger();
$logger->addWriter($writer);
$logger->info('Informational message', ['user' => 'administrator']);
输出如下内容:
2014-12-01T13:00:00+00:00 INFO (6): Informational message {"user":"administrator"}