In modern PHP Enterprise System Applications, its crucial to have the ability to get alerted when an error happen. One way to do it is using Slack. You may follow this recipe:

Prerequisites:

Step 1. Install the "symfony/slack-notifier" package using composer:

composer require symfony/slack-notifier

Step 2. Create a Slack incoming webhook URL by following the instructions on Slack's website: https://api.slack.com/messaging/webhooks

Step 3. Configure the Slack notifier by adding the following lines to your Symfony application's config/packages/prod/monolog.yaml file:

monolog:
    handlers:
        slack:
            type: slack
            level: error
            webhook_url: 'https://hooks.slack.com/services/your/incoming/webhook/url'

Note that you should replace the webhook_url with the one you created in step 2.

Step 4. You can customize the notification message by creating a custom formatter. Add the following to your config/packages/prod/monolog.yaml file:

monolog:
    handlers:
        slack:
            type: slack
            level: error
            webhook_url: 'https://hooks.slack.com/services/your/incoming/webhook/url'
            formatter: 'App\Logging\SlackFormatter'

Step 5. Create a custom formatter by creating a new class in your Symfony application's src/Logging/ directory:

<?php

namespace App\Logging;

use Monolog\Formatter\NormalizerFormatter;

class SlackFormatter extends NormalizerFormatter
{
    /**
     * @param array $record
     * @return array
     */
    public function format(array $record): array
    {
        $data = parent::format($record);
        
        $message = "An exception occurred:\n\n";
        $message .= "```";
        $message .= $data['message']."\n";
        $message .= $data['context']['exception']."\n";
        $message .= "```";
        
        $data['message'] = $message;
        
        return $data;
    }
}

Note that this is just an example formatter. You can customize it as you like to fit your needs.

Step 6. Now, when an exception occurs in your Symfony application, it will be logged to the Slack channel you configured. You can test this by intentionally causing an exception in your application and checking your Slack channel for the notification.

Read more about the Symfony Slack Notifier component.

 

Related Videos