Search code examples
symfonymailermonolog

How to configure sending errors by e-mail with Symfony 5.1, Monolog and Mailer component?


Do you have an example configuration to send logs by email with the Mailer component of Symfony 5.1.

In the Symfony blog we announce this feature, but I can't put the right config in monolog.yaml

https://symfony.com/blog/new-in-symfony-5-1-misc-improvements-part-3 : That's why in Symfony 5.1 we added a new Monolog log handler which uses the Mailer component to send the logs via email.


Solution

  • Unfortunately this addition only covers the actuall MailerHandler class in the monolog-bridge. This does not cover the possibility to configure it in the monolog-bundle (that's the drawback if those components are distributed over multiple packages).

    The PR for the change in the monolog-bundle is still open, and can be found here: Add Symfony Mailer support #354.

    If you don't want to wait for the change in the monolog-bundle you could already use it by defining the handler as a service and then using it with the service type in the monolog configuration.

    So define your service:

    services:
        # this configures the "mail" as a prototype, so you can
        # define the sender and recipient mail addresses here
        symfony_mailer_service_template:
            class: Symfony\Component\Mime\Email
            calls:
                - ['from', ['[email protected]']]
                - ['to', ['[email protected]']]
                - ['subject', ['Logs']]
    
        symfony_mailer_service:
            class: Symfony\Bridge\Monolog\Handler\MailerHandler
            arguments:
                - '@mailer.mailer'
                - '@symfony_mailer_service_template'
                - !php/const Monolog\Logger::DEBUG # log level
                - true # bubble
    

    And then in your mailer configuration you could use it like this:

    monolog:
        handlers:
            main:
                type: fingers_crossed
                handler: deduplicated
    
            deduplicated:
                type:    deduplication
                handler: symfony_mailer
    
            symfony_mailer:
                type: service
                id: symfony_mailer_service