我正在开发Zend Framework 2,并希望扩展我的请求网址定制的日志记录。
这样做的最佳方式是什么。我可以将$ _REQUEST onBootstrap传递给记录器并通过覆盖记录器类来使用它吗?
日志记录应如下所示:
2015-10-05T09:52:49+02:00 CRIT (2): Log Message, Request URL: http://www.website.com/page?field=value&....
module.config看起来如下:
'log' => array(
'Log\ErrorHandler' => array(
'writers' => array(
array(
'name' => 'stream',
'options' => array(
'stream' => 'logs/php.log',
)
)
),
),
'Log\ExceptionHandler' => array(
'writers' => array(
array(
'name' => 'stream',
'options' => array(
'stream' => 'logs/exception.log',
)
)
),
),
'Log\Main' => array(
'writers' => array(
array(
'name' => 'stream',
'options' => array(
'stream' => 'logs/main.log',
)
)
),
),
)
或者我可以在某处挂钩所有记录器以将请求添加到额外的数组中,就像您在记录某些内容时所做的那样:
$this->getServiceLocator()->get('Log\Main')->crit('Log Message', ['request' => $this->getRequest()]);
答案 0 :(得分:2)
您可能希望在日志服务中添加处理器。
$logger->addProcessor(new LogExtra());
class LogExtra implements ProcessorInterface
{
public function process(array $event)
{
if (!isset($event['extra'])) {
$event['extra'] = array();
}
$event['extra']['request'] = // value you want to log
return $event;
}
}
答案 1 :(得分:1)
谢谢@ Ed209, 你的回答让我走上正轨。
我已经添加了一个新处理器并实现了ServiceLocatorAwareInterface:
<?php
namespace Your\Namespace\ToProcessor;
use Zend\Log\Processor\ProcessorInterface;
use Zend\ServiceManager\ServiceLocatorAwareInterface;
use Zend\ServiceManager\ServiceLocatorInterface;
/**
* Class Request
*
* Processor adds some request information to the logger extra
*
*/
class RequestInformation implements ServiceLocatorAwareInterface, ProcessorInterface
{
/**
* Service Locator
*
* @var \Zend\Di\ServiceLocator
*/
protected $serviceLocator = null;
/**
* Processes the given event and adds request information to the extras
*
* @param array $event
* @return array
*/
public function process(array $event)
{
if (!isset($event['extra'])) {
$event['extra'] = array();
}
$request = $this->getServiceLocator()->getServiceLocator()->get('Request');
if ($request instanceof \Zend\Http\Request) {
$event['extra']['requestUrl'] = $request->getUriString();
} elseif ($request instanceof \Zend\Console\Request) {
$event['extra']['consoleParameters'] = $request->toString();
}
return $event;
}
/**
* Set service locator
*
* @param ServiceLocatorInterface $serviceLocator
*/
public function setServiceLocator(ServiceLocatorInterface $serviceLocator) {
$this->serviceLocator = $serviceLocator;
}
/**
* Get service locator
*
* @return ServiceLocatorInterface
*/
public function getServiceLocator() {
return $this->serviceLocator;
}
}
并更改了我的module.config:
的配置&#39;登录&#39; =&GT;阵列(
'Log\Main' => array(
'writers' => array(
array(
'name' => 'stream',
'options' => array(
'stream' => 'logs/main.log',
)
)
),
'processors' => array(
array(
'name' => '\PathToProcessor\RequestInformation'
)
)
),
)