PHP: How to use monolog to log to console (php://out)?
Some extra details if you want to tweak the default message formatting at the same time:
use Monolog\Logger;
use Monolog\Formatter\LineFormatter;
use Monolog\Handler\StreamHandler;
$output = "[%datetime%] %channel%.%level_name%: %message%\n";
$formatter = new LineFormatter($output);
$streamHandler = new StreamHandler('php://stdout', Logger::DEBUG);
$streamHandler->setFormatter($formatter);
$logger = new Logger('LoggerName');
$logger->pushHandler($streamHandler);
The solution is rather simple. Since the example shows a StreamHandler
it's possible to pass in a stream (instead of the path to a file). By default, everything that is echo'ed in PHP is written to php://stdout / php://output so we can simple use one of those as stream for the StreamHandler
:
<?php
use Monolog\Logger;
use Monolog\Handler\StreamHandler;
// create a log channel
$log = new Logger('name');
$log->pushHandler(new StreamHandler('php://stdout', Logger::WARNING)); // <<< uses a stream
// add records to the log
$log->warning('Foo');
$log->error('Bar');
Hope this saves somebody some time :)