phpemailhandlermonolog

Seldaek/monolog NativeMailerHandler not working with DeduplicationHandler


I have a project setup with monolog for error reporting. The code bellow is an example of how its setup.

$streamHandler = new StreamHandler(
    "$_ENV[ROOT_DIR]/logs/app.log",
    Level::Debug
);
$streamHandler->setFormatter(new LineFormatter(null, "y:m:d h:i:s", true));

$mailHandler = new NativeMailerHandler(
    $_ENV['ERROR_NOTIFICATION_EMAIL'],
    'Error from My Site',
    'no-reply@mydomain',
    Level::Error
);

$handlers = [
    new DeduplicationHandler($streamHandler),
    new DeduplicationHandler($mailHandler)
];

$processors = [
    new UidProcessor(),
    new IpProcessor(),
    new WebProcessor(),
];
$logger = new Logger('app', $handlers, $processors);

I'm using a custom setup not symphony, the issue is that in this setup, the mailHandler never sends any emails. Deduplication works perfectly for the stream handler but not for the mail handler. The other setups I've seen online using other mailers like swift_mailer all seem to be configured this way so I'm not sure why this doesn't work.

Just adding some clarification, the mailHandler does work when not wrapped in the DeduplicationHandler.


Solution

  • So I figured it out, the functioning code is bellow:

    $streamHandler = new StreamHandler(
        "$_ENV[ROOT_DIR]/logs/app.log",
        Level::Debug
    );
    $streamHandler->setFormatter(new LineFormatter(null, "y:m:d h:i:s", true));
    
    $mailHandler = new NativeMailerHandler(
        $_ENV['ERROR_NOTIFICATION_EMAIL'],
        'Error from My Site',
        'no-reply@mydomain',
        Level::Error
    );
    
    $groupedHandlers = new GroupHandler([
        $streamHandler,
        $mailHandler
    ]);
    
    $deduplicatedHandler = new DeduplicationHandler($groupedHandlers);
    
    $processors = [
        new UidProcessor(),
        new IpProcessor(),
        new WebProcessor(),
    ];
    $logger = new Logger('app', [$deduplicatedHandler], $processors);
    

    The problem was caused by having two deduplication handlers. Perhaps this is the intended behaviour of Monolog, but I was unaware of it. The solution was to group the handlers before deduplicating them.

    Hope this helps if someone has the same or similar issue, the order of things matters with Monolog!