# Sending Laravel Logs to Mattermost Channels

[Mattermost](https://mattermost.com/) is an open-source platform for communication and collaboration with integrations with many tools. It is mostly considered as an open-source alternative to Slack and Microsoft Teams.

Although Laravel does not have an official [log channel driver](https://laravel.com/docs/9.x/logging#available-channel-drivers) for Mattermost, we can build a custom [Monolog](https://github.com/Seldaek/monolog) handler that can be easily configured in Laravel apps.

I have created a small [package](https://github.com/muhamadhhassan/laramost) for this purpose that, unlike the existing Mattermost handlers, format the message according to Mattermost [docs](https://developers.mattermost.com/integrate/webhooks/incoming/#parameters)

## Installation

```bash
$ composer require muhamadhhassan/laramost
```

## Configuration

In your `config/logging.php` file, add the `mattermost` channel to the `channels` array:

```php
use LaraMost\Formatter\MattermostFormatter;
use LaraMost\Handler\MattermostWebhookHandler;

'channels' => [
    'mattermost' => [
        'driver'  => 'monolog',
        'handler' => MattermostWebhookHandler::class,
        'formatter' => MattermostFormatter::class,
        'with' => [
            'hook' => 'https://your-mattermost.com/hooks/random-string',
        ],
        'level' => 'error'
    ],
],
```

You can follow the steps [here](https://developers.mattermost.com/integrate/webhooks/incoming/#create-an-incoming-webhook) to create an incoming webhook for your channel.

### Levels

Monolog levels are used to set the message color and icon

| Level Name | Level Value | Color   | Emoji |
|------------|-------------|---------|-------|
| DEBUG      | 100         | #91C4EB | 🔍|
| INFO       | 200         | #91C4EB | ℹ|
| NOTICE     | 250         | #99cc33 | 📝|
| WARNING    | 300         | #ffcc00 | ⚠|
| ERROR      | 400         | #cc3300 | 🐛|
| CRITICAL   | 500         | #cc3300 | ❌|
| EMERGENCY  | 600         | #cc3300 | 🚨|

## Usage

Simply, using Laravel `Log` facade

```php
Log::channel('mattermost')->error('Something went wrong', ['user_id' => 5]);
```

Will send the following message to your mattermost channel:

![Screenshot 2022-09-23 172832.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1663973166282/NGfimPR4F.png align="left")

> ⚠ **Warning**: When you log to the `mattermost` channel make sure that the level is greater than or equals the one defined in `config/logging.php`

And there you have it! A simple implementation to send log records to a Mattermost channel.
