Send Laravel Log to Slack Notification

Laravel provides robust logging services that allow you to log messages to Slack to notify your entire team.

There are two main and very easy steps to prepare Slack and Laravel to connect with each other.

In slack dashboard go to: Administration / Manage apps













Press the button of Add to Slack.

In the new window it will ask you to select one of your slack channels and then press Add Incoming WebHooks Integration.



Then a new window will show you the WebHooks URL:


At the end of this page you see the button of Save Settings. Press it to save.

Copy the WebHooks URL We need to set it in Laravel .env file.


As soon as the WebHooks url is generated you will see a notice inside the channel you selected like below:

Now put this line in Laravel .env file

LOG_SLACK_WEBHOOK_URL=WebHooks-URL

In Laravel 6 the config file of Logging is different with older versions. Let’s have a look at config/logging.php file.

By default, Laravel will use the stack channel when logging messages. The stack channel is used to aggregate multiple log channels into a single channel. Which after a fresh Laravel installation it is set to only accept ‘daily’.

So edit the config/logging.php file and set ‘slack’ as the second channel for logging Laravel messages as below.








Then since we changed the .env and a config file we need to clear and again cache Laravel configurations by:

php artisan config:cache

As you see in slack channel the level of Logging is set to debug!








The level option determines the minimum “level” a message must be in order to be logged by the channel. All of the log levels defined in the RFC 5424 specification: emergency, alert, critical, error, warning, notice, info, and debug. You may write information to the logs using the Log facade like:

Log::emergency($message);
Log::alert($message);
Log::critical($message);
Log::error($message);
Log::warning($message);
Log::notice($message);
Log::info($message);
Log::debug($message);


Then in the web.php file I do this change:

Route::get('/', function () {
Log::critical('This is a critical message Sent from Laravel App');
return view('welcome');
});
and refresh (trigger) the Laravel app main page. And you will see in your Slack channel the message:




Comments

Popular posts from this blog

Laravel Database Transactions