7

How can I configure Monolog to output PHP errors within the response, as would have been done without Monolog?

What I want to do is when, for example, a PHP E_ERROR occurs within a PHP page, that error message will be output to the response, and also passed to any other Handlers set for Monolog.

AFAIK, I might use StreamHandler and have it output to stdout, but don't know how to do this or if it will work as expected?

There are two variations I'd like the option of:

  1. Monolog re-formats the error message before having it output within the response
  2. Monolog relays the error (or exception) back to PHP native error handling so that it outputs the message in the same format in the response as if Monolog was not mediating it

How could I achieve these? I don't even know how I can get Monolog to register itself as a handler for exceptions and errors. Would I need to write my own functions to pass to register_error_handler(), register_exception_handler() and register_shutdown_function()?

Jodes
  • 14,118
  • 26
  • 97
  • 156

2 Answers2

13

Short version:

use Monolog\ErrorHandler;
$logger = new Logger('Logger Name');

ErrorHandler::register($logger);

Longer, more customizable version:

use Monolog\ErrorHandler;

$logger = new Logger('Logger Name');

$handler = new ErrorHandler($logger);
$handler->registerErrorHandler([], false);
$handler->registerExceptionHandler();
$handler->registerFatalHandler();
Loupax
  • 4,728
  • 6
  • 41
  • 68
  • Have implemented your solution but Ive run into some problems .Please look at my question http://stackoverflow.com/questions/43665088/set-minimum-php-error-reporting-in-monolog-errorhandler – Stanley Ngumo Apr 27 '17 at 20:33
  • 3
    This works for logging php errors but does not preserve the normal php functionality of outputting PHP errors within the response. Is there something else I should be doing? – Josh Bernfeld Apr 26 '18 at 03:22
  • Actually yes. Make sure that the sedond parameter of registerErrorHandler is TRUE. If it is false, the PHP error handler will not be called. And forget about my response below... – Ralf Jahr Apr 17 '19 at 12:25
2

I also wanted to preserve the default behaviour, i.e., error messages in the response. Just receiving blank pages (which happens at least with Monolog 1 and PHP 7.2) is not very intuitive, at least during development. My solution was to add the following handler:

$log->pushHandler(new Monolog\Handler\StreamHandler("php://output", Monolog\Logger::ERROR));
Ralf Jahr
  • 312
  • 2
  • 18