Laravel/Lumen errors handler & Slack
I have been working in a project where it’s quite common that other dependent services will be down for minutes. And it’s not also possible to keep an eye on your log files to see what’s going wrong when you’re constantly logging lots of data and thousands of requests are coming per minute. So, in that case, you may want to integrate some other services or monitoring tool that will instantly notify me about these scenarios. So, slack is a good choice which comes pre-integrated with Laravel/Lumen.
To integrate Slack with Laravel, all you need is a slack URL. Laravel documentation is quite straight forward. But, in case you’re facing trouble, you may just go through the code or you need to be spoon fed like me.
First of all, you need is a slack URL. You can get a slack account and add a webhook from here. When you have the webhook URL, place it in your .env
file with the key LOG_SLACK_WEBHOOK_URL
. Now in your config/logging.php
file, you can change your
username
emoji
for the usernamelevel
When you’re done updating these variables, you’re just done. All you need to do is,
app('log')->channel('slack')->error('Hitting first log to slack');
This will send a log to slack. That’s it. It’s that easy. The level is an important key to this configuration. If the level is set to a higher than you’re trying to log, it won’t get logged.
Tweaks
- When you created the webhook URL, you attached a default channel name. In case you want to change the channel name, add a key
channel
to yourslack
configuration array. - If you don’t want your messages to be long, you can use
short
as a key toslack
configuration and set it totrue
- You can change the username who’ll be sending those logs. Just change the
username
value in yourslack
array. - Most importantly, you need to change the
level
value of yourslack
configuration. This denotes what type of logs will be sent to Slack. You can have a look at the levels. bubble
means, if you’re handing multiple drivers for logging after it handles Slack, it won’t log to other logs even if it meets the log level.context
means, if you’re passingarray
andstring
both at the same time, it’ll format the array and log to the channel.
- For learning what are the permitted keys that you can use, take a look in this file.
That’s my two cents. Happy coding. ❤