简体   繁体   中英

Using monolog and whoops

I am trying to using Monolog in the set_exception_handler and set_error_handler , while Whoops outside.

I tried 2 locations for running Whoops.

  1. Run Whoops #1 Location
    • Result: Monolog logs the error/exception and Whoops doesn't display
  2. Run Whoops #2 Location
    • Result: Monolog doesn't log anything and Whoops displays

I am stuck on why I am not able to get both Monolog and Whoops to work together.

...
use Whoops\Run;
use Whoops\Handler\PrettyPageHandler;

error_reporting(E_ALL);
ini_set('display_errors', 1);
//Run Whoops #1 Location
$whoops = new Run();
$whoops->prependHandler(new PrettyPageHandler());
$whoops->register();

function exceptionHandler($e)
{ 
    //log the exception using monolog
}

function errorHandler($errno, $errstr, $errfile, $errline)
{
    //log the error using monolog
}

set_error_handler("errorHandler");
set_exception_handler('exceptionHandler');

//Run Whoops #2 Location

The set_exception_handler function in php is overridden by the Whoops library. We can use the Whoops library's pushHandler method to register a generic handler function, and initialise Monolog inside of that function:

use Monolog\Formatter\LineFormatter;
$whoops = new \Whoops\Run;
$whoops->pushHandler(function($exception, $inspector, $run) {

   // Initialise Monolog here. Example with stack trace support:
    $formatter = new LineFormatter(
        LineFormatter::SIMPLE_FORMAT, 
        LineFormatter::SIMPLE_DATE
    );
    $formatter->includeStacktraces(true);
    $errlog = new Logger('Error Log');
    $stream = new StreamHandler("logs/error.log", Logger::ERROR);
    $stream->setFormatter($formatter);
    $errlog->pushHandler($stream);
    $errlog->error($exception);

    return Handler::DONE;       
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM