47

I just switched to monolog and wanted to log my message to the PHP console instead of a file. This might seem obvious for some people, but it took me a little while to figure out how to do that and I couldn't find a similar question/answer on SO.

The example on Monolog's Github readme only shows how to use a file:

<?php

use Monolog\Logger;
use Monolog\Handler\StreamHandler;

// create a log channel
$log = new Logger('name');
$log->pushHandler(new StreamHandler('path/to/your.log', Logger::WARNING)); // <<< uses a file

// add records to the log
$log->addWarning('Foo');
$log->addError('Bar');

But it doesn't state anywhere how messages can be logged to the console. After searching on Google, I landed either on a help page for Symfony or questions of people looking for a way to log to the browser console.

Stephan Vierkant
  • 9,674
  • 8
  • 61
  • 97
Hirnhamster
  • 7,101
  • 8
  • 43
  • 73

2 Answers2

96

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 :)

Márton Tamás
  • 2,759
  • 1
  • 15
  • 19
Hirnhamster
  • 7,101
  • 8
  • 43
  • 73
  • 1
    this works however i would like to know how to archive the both i.e show the output in the console AND write to a file ? – mahen3d Feb 23 '17 at 04:30
  • 2
    @mahen3d add another handler to do that for you (```$log->pushHandler(new StreamHandler('/path/to/log/file', Logger::NOTICE))```) – georaldc Apr 24 '17 at 19:15
22

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);
Pádraig Galvin
  • 1,065
  • 8
  • 20
Justin Tilson
  • 833
  • 1
  • 10
  • 12