Steven
Steven

Reputation: 43

How to send a mail with PHPMailer from Monolog when an error occurs

I'm using Monolog (https://github.com/Seldaek/monolog) in my project and we want to receive an email when there are errors in our application. The logs are working as expected but if the log level is ERROR (below log level is DEBUG), I want the logger to send me an email.

I tried to use the class NativeMailHandler but it doesn't seems to work and I would prefer to use our SMTP mail server (works great in PHP but I can't figure out how to link it with Monolog error handler)

$logger = new Logger('LOG');
$logHandler = new StreamHandler('synchro.log',Logger::DEBUG);
$logger->pushHandler($logHandler);

Upvotes: 3

Views: 3306

Answers (2)

Filip Š
Filip Š

Reputation: 756

I created PHPMailer handler for Monolog. It enables you to send logs to emails with PHPMailer.

It is available on GitHub and Packagist, but it can also be used without Composer (which requires manual installation of Monolog and PHPMailer).

<?php

use MonologPHPMailer\PHPMailerHandler;

use Monolog\Formatter\HtmlFormatter;
use Monolog\Logger;
use Monolog\Processor\IntrospectionProcessor;
use Monolog\Processor\MemoryUsageProcessor;
use Monolog\Processor\WebProcessor;

use PHPMailer\PHPMailer\PHPMailer;

require __DIR__ . '/vendor/autoload.php';

$mailer = new PHPMailer(true);
$logger = new Logger('logger');

$mailer->isSMTP();
$mailer->Host = 'smtp.example.com';
$mailer->SMTPAuth = true;
$mailer->Username = '[email protected]';
$mailer->Password = 'password';

$mailer->setFrom('[email protected]', 'Logging Server');
$mailer->addAddress('[email protected]', 'Your Name');

$logger->pushProcessor(new IntrospectionProcessor);
$logger->pushProcessor(new MemoryUsageProcessor);
$logger->pushProcessor(new WebProcessor);

$handler = new PHPMailerHandler($mailer);
$handler->setFormatter(new HtmlFormatter);

$logger->pushHandler($handler);

$logger->error('Error!');
$logger->alert('Something went wrong!');

Upvotes: 4

Steven
Steven

Reputation: 43

Well, I found a solution to my problem, maybe it will help someone one day:

Since the class NativeMailHandler is using the mail() php function. I changed the code in monolog/monolog/src/Monolog/Handler/NativeMailhandler.php of the function send() and I declared my PHPMailer() there instead of the mail() function.

    $mailHandler = new NativeMailerHandler([email protected], $subject, $from,Logger::ERROR,true, 70);

    $logHandler = new StreamHandler('synchro.log',Logger::DEBUG);

    $logger->pushHandler($logHandler);
    $logger->pushHandler($mailHandler); //push the mail Handler. on the log level defined (Logger::ERROR in this example), it will send an email to the configured mail in the send() function in monolog/monolog/src/Monolog/Handler/NativeMailhandler.php

Upvotes: 0

Related Questions