如何创建自定义日志(使用 Zend2)并为每个日志事件设置用户名。这是我如何尝试的示例:
public function log( )
{
$log_file = 'path/to/logfile.log';
$format = '%timestamp% %priorityName% (%username%) %message%';
$formatter = new ZendLogFormatterSimple($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
谢谢!
您可以使用
日志方法的第三个参数 extra
- 额外数据数组,这些数据被转换为 json 并通过格式化程序自动添加到日志消息中(Zend\Log\Formatter\Simple::format)
简单的例子:
$writer = new ZendLogWriterStream('php://output');
$logger = new ZendLogLogger();
$logger->addWriter($writer);
$logger->info('Informational message', ['user' => 'administrator']);
输出如下内容:
2014-12-01T13:00:00+00:00 INFO (6): Informational message {"user":"administrator"}