Honeybadger With Monolog in Symfony

I have a project in which I need to use Honeybadger to log errors. It’s a Symfony 6.2 application and I’m already using Monolog for logging. Extensive searching for info about Monolog, Symfony and Honeybadger turned up almost nothing. So, here’s some quick notes on how I set it up.

I specifically want to log anything of debug or higher level (so, all levels) for reports on the app channel. And only notice level or above for anything else (like event, doctrine, etc). So I had to create 2 service definitions for my custom handler class with different Level arguments passed to them. You can’t specify level the way you do for built in handlers unfortunately.

# config/packages/dev/monolog.yaml
monolog:
    handlers:
        main:
          honeybadger_main:
             type: service
             id: monolog.handler.honeybadger.notice             
             channels: ["!app"]        
         honeybadger_app:
             type: service
             id: monolog.handler.honeybadger.debug
             channels: ["app"]

services:
    monolog.handler.honeybadger.notice:
        class: App\Logger\HoneyBadgerHandler
        arguments:
            $container: '@service_container'
            $level: !php/const Monolog\Level::Notice
    monolog.handler.honeybadger.debug:
        class: App\Logger\HoneyBadgerHandler
        arguments:
            $container: '@service_container'
            $level: !php/const Monolog\Level::Debug

And my custom monolog handler class which feeds the logged records to Honeybadger:

<?php
namespace App\Logger;

use Honeybadger\Honeybadger;
use Monolog\Handler\AbstractProcessingHandler;
use Monolog\Level;
use Monolog\LogRecord;
use Symfony\Component\DependencyInjection\ContainerInterface;

class HoneyBadgerHandler extends AbstractProcessingHandler
{
    private Honeybadger $honeyBadger;
    private ContainerInterface $container;

    public function __construct(ContainerInterface $container, int|string|Level $level = Level::Debug, bool $bubble = true)
    {
        $this->container = $container;
        $this->honeyBadger = Honeybadger::new([
            'api_key' => $_ENV['HONEYBADGER_KEY'],
            'environment_name' => $this->container->getParameter('kernel.environment'),
        ]);
        parent::__construct($level, $bubble);
    }

    protected function write(LogRecord $record): void
    {
        if($record->level->value < $this->level->value){
            return;
        }

        $this->honeyBadger->customNotification([
            'title'   => $record->channel . '.'.$record->level->getName(),
            'message' => $record->formatted,
        ]);
    }

}

Leave a Reply

Your email address will not be published. Required fields are marked *