Skip to content

Instantly share code, notes, and snippets.

@greenbicycle
Last active August 20, 2018 22:50
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save greenbicycle/645a021a7516760e8c0c03eef3839f83 to your computer and use it in GitHub Desktop.
Save greenbicycle/645a021a7516760e8c0c03eef3839f83 to your computer and use it in GitHub Desktop.
Make Laravel use SlackHandler for Logging
/*
I am using Laravel 5.2. This will probably work for many versions, but use at your own risk.
Instructions
- Make sure that you add SLACK_TOKEN, SLACK_CHANNEL, SLACK_USERNAME, SLACK_ICON in .env
- SLACK_ICON - you can use almost any emoji that Slack supports. See http://www.emoji-cheat-sheet.com/
- SLACK_USER - You can use any username you want to. It doesn't have to be an existing user
- SLACK_CHANNEL - I don't know what happens if you use a non-existent channel. I always make sure the channel exists first
- SLACK_TOKEN - You can find this in your Slack account somewhere
- Add the code below to the top of bootstrap/app.php
- That is it. Now \Log::warning("This is a warning"); should send a message to Slack.
*/
// Put this at very top of file.
use Monolog\Handler\SlackHandler;
// There is a line that starts $app = ...
// The rest goes after that line
$app->configureMonologUsing( function($monolog) {
$slackHandler = new SlackHandler(env('SLACK_TOKEN'), env('SLACK_CHANNEL'), env('SLACK_USERNAME'), true, env('SLACK_ICON'));
$slackHandler->setlevel(Monolog\Logger::INFO);
$monolog->pushHandler($slackHandler);
});
// The rest goes in .env
SLACK_TOKEN=<your slack token here>
SLACK_CHANNEL=#test-channel
SLACK_USERNAME=logger
SLACK_ICON=:squirrel:
// Put this in routes.php to test SlackHandler (or whatever handler you are using.)
// Then visit /logtest and check Slack.
Route::get('logtest', function() {
\Log::debug("This is debug information.");
\Log::info("This is soley for informational purposes.");
\Log::notice("This is a notice.");
\Log::warning("This is a warning. Maybe this shouldn't happen so often.");
\Log::error("This is an error message. Please fix this soon.");
\Log::critical("This is a critical warning. That is going to hurt in the morning!");
\Log::alert("Alert! Danger Will Robinson.");
\Log::emergency("This is an emergency. All hands abandon ship!");
});
@greenbicycle
Copy link
Author

image

If you have done it right, this is what Slack will look like.

@dharkness
Copy link

How does this differ from using the builtin slack driver in config/logging.php?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment