我们有一个旧的应用程序部分,尚未使用 Monolog。该应用程序一次需要日志的整个输出,以便它可以将其打印在仅对开发人员可见的隐藏 div 中。
很像实时调试...
问题是我不知道如何让 Monolog 记录到数组或设置局部变量的处理程序,或者从代码特定部分的日志中获取输出。
这是我到目前为止想到的:
protected function getHandlers()
{
$handlers = array();
$logsDir = $this->getLogsDir();
$logFile = $logsDir . DIRECTORY_SEPARATOR . 'application.log';
$logfileHandler = new \Monolog\Handler\FingersCrossedHandler($logFile, Logger::ERROR);
array_push($handlers, $logfileHandler);
// When in CLI, we're going to push the logs through STDERR as well
// This way, if needed, we can easily redirect STDERR to STDOUT or to some specified file
if (php_sapi_name() == 'cli') {
$stderrHandler = new StreamHandler('php://stderr', Logger::INFO);
array_push($handlers, $stderrHandler);
}
return $handlers;
}
有人知道哪个处理程序适合吗? (欢迎举例)
对于具有相同逻辑柱的人来说没问题。 我用自定义处理程序完成了它:
<?php
namespace Log\Handler;
use Monolog\Logger;
use Monolog\Handler\AbstractProcessingHandler;
/**
* Description of runtimeHandler
*
* @author Sinisa Culic <[email protected]>
*/
class RuntimeHandler extends AbstractProcessingHandler
{
protected $log;
/**
* @param integer $level The minimum logging level at which this handler will be triggered
* @param Boolean $bubble Whether the messages that are handled can bubble up the stack or not
*/
public function __construct($level = Logger::DEBUG, $bubble = true)
{
parent::__construct($level, $bubble);
}
/**
* {@inheritdoc}
*/
public function close()
{
return $this->log;
}
/**
* {@inheritdoc}
*/
protected function write(array $record)
{
$this->log[] = $record;
}
}
另一个选择是使用 Monolog 提供的 TestHandler,因为它在内部将日志记录存储在一个可以轻松检索的数组中。
这是一个例子:
$logger = new Logger('custom');
$handler = new TestHandler(Level::Info);
$logger->pushHandler($handler);
// Use the logger in the legacy code
// Get the array of LogRecord
$records = $handler->getRecords();
// Extract out the formatted log entries
$logs = array_column($records,'formatted');