Search code examples
phpslimmonologslim-3

How to get an email with log details when errors occur with Slim and Monolog


My website is built over Slim Framework V3, and uses Monolog. I want to get an email notification when something goes wrong on my website (any log message above Error). In other words, I want to know when a Critical, Alert or Emergency message is logged.

Ideally, I want to also get the logs right before the error also in the same email, to make it easier to debug.

This is my current Monolog configuration (Slim default):

// monolog
$container['logger'] = function ($c) {
    /** @var \Slim\Container $c */
    $settings = $c->get('settings')['logger'];
    $logger = new Monolog\Logger($settings['name']);
    $logger->pushProcessor(new Monolog\Processor\UidProcessor());

    $logger->pushHandler(new Monolog\Handler\StreamHandler($settings['path'], $settings['level']));

    return $logger;
}

These are the log settings:

return [
    // Monolog settings
    'logger' => [
        'name' => 'slim-app',
        'path' => __DIR__ . '/logs/' . $logDate->format('Y-m-d') . '_app.log', //TODO: Make sure logs are above DocumentRoot
        'level' => \Monolog\Logger::DEBUG,
    ]
];

Solution

  • I came up with a solution which involves the standard StreamHandler, the NativeMailHandler and the FingersCrossedHandler.

    The StreamHandler simply logs everything above the given level, which is fine.

    Now, the trick to get detailed emails when a certain level of error happens is to combine a NativeMailHandler with a FingersCrossedHandler.

    // monolog
    $container['logger'] = function ($c) {
        /** @var \Slim\Container $c */
        $settings = $c->get('settings')['logger'];
        $logger = new Monolog\Logger($settings['name']);
        $logger->pushProcessor(new Monolog\Processor\UidProcessor());
    
        $logger->pushHandler(new Monolog\Handler\StreamHandler($settings['path'], $settings['level']));
    
        //Handler to send email on critical (or above) errors
        //Uses the FingersCrossed strategy which buffers all messages preceeding the critical error
        $dt = new DateTime();
        $mailHandler = new Monolog\Handler\NativeMailerHandler(
            '[email protected]', //TODO: The email address where to send emails
            '[ERROR] : Unexpected error happened that requires immediate attention ' . $dt->format('Y-m-d'),
            '[email protected]',
            $settings['level'],
            true,
            2000
        );
        $logger->pushHandler(new Monolog\Handler\FingersCrossedHandler($mailHandler, Monolog\Logger::CRITICAL));
    
        return $logger;
    };
    

    These are my logger settings (in settings.php):

    return [
        // Monolog settings
        'logger' => [
            'name' => 'slim-app',
            'path' => __DIR__ . '/logs/' . $logDate->format('Y-m-d') . '_app.log', //TODO: Make sure logs are above DocumentRoot
            'level' => \Monolog\Logger::DEBUG,
        ]
    ];
    

    How it works

    According to the monolog source code, the FingersCrossedHandler does the following :

    Only requests which actually trigger an error (or whatever your actionLevel is) will be in the logs, but they will contain all records, not only those above the level threshold.

    Therefore, this statement will make sure our NativeMailerHandler is used by the FingersCrossedHandler when a message with level Critical or more is called:

    new Monolog\Handler\FingersCrossedHandler($mailHandler, Monolog\Logger::CRITICAL)
    

    Hope this helps someone!