Sangoku
Sangoku

Reputation: 1606

Get Monolog to log to an Array

We have an old Application part which does not use Monolog yet. This application needs on one time the whole output from the log so it can print it out in a hidden div visible only for developers.

Much like live debug...
The problem is I can't figure out how to get Monolog to log to an array or set the handler for a local variable, or to get the output from the log on a particular part of code.

This is what I came up with until now:

 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;
    }

Anyone any idea which handler is suitable for that? (examples are welcome)

Upvotes: 1

Views: 1435

Answers (2)

ttk
ttk

Reputation: 417

Another option is to use the Monolog supplied TestHandler, as internally it stores the log records in an array which can be easily retrieved.

Here's an example:

$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');

Upvotes: 1

Sangoku
Sangoku

Reputation: 1606

Ok for thouse who have the same logical columdrum. I did it with a custom custom handler:

<?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;
    }

}

Upvotes: 1

Related Questions