Logging Exceptions via Slack in Laravel

Logging can be a powerful tool that people tend to gloss over. Most developers still view logging as an archaic way of dealing with bugs and user issues. Laravel has a very easy and eloquent way of dealing with the logging problem.

The Problem

Logging is usually done by creating a log file on your server, and telling your backend to send all errors to that file. While this is a good temporary solution, this system tends to fill up fast, and is a pain to search and find certain things.

The Solution (one of many)

Using Laravel’s built-in logging system, you can log to many different “channels”, including our old tried and true, file logging on the server. But that isn’t why you are reading this post, is it?

Slack it to me

If you have ever used Slack, you’ve grown to love the instant messaging capabilities, and the searching function. Search is great on Slack. And one of our problems with logging was search, wasn’t it? Wouldn’t it be great if we could log all our errors to Slack? Good news!

How to log exceptions to Slack

Logging is relatively easy in Laravel (see this page for how-to setup Slack logging). What we want is to nicely log all our exceptions.

This post is written assuming you have a Laravel project already set up.

Open your app/Exceptions/Handler.php handler file. This is where Laravel gives you the option to send exceptions to Sentry, Bugsnag, or any other bug reporters you want to set up. This is also where we will be logging to our Slack channel.

public function report(Exception $exception)
{
    parent::report($exception);
}

We are going to change this function to do a few things.

  1. Log to Slack (that is why you are here!)
  2. Format the exception nicely.
  3. We will do an optional filter to filter out any vendor code.
  4. Remove the parent::report($exception) as we are going to be doing this ourselves.

Our function will now look like this:

public function report(Exception $exception)
{
    // You can specify which exceptions not to report here
    if ($this->shouldntReport($exception)) {
        return;
    }

    // We are getting the directory so we can filter out any vendor code,
    // along with the directory, so it looks better for the developer.
    $dir = substr(__DIR__,0,-14);
    $backtrace =  $exception->getTraceAsString();
    $backtrace = str_replace([$dir],"", $backtrace);
    $backtrace = preg_replace('^(.*vendor.*)\n^','',$backtrace);

    // And finally, we log the exception! 
    Log::channel('slack')->error('@here'.PHP_EOL.' . PHP_EOL . '**Error:** '.$exception->getMessage() . PHP_EOL. '**Line:** ' . $exception->getLine() . PHP_EOL. '**File:** '. $exception->getFile() . PHP_EOL . '**Trace:**'.PHP_EOL. $backtrace);
}

And that’s it! It is very easy to nicely log your exceptions using Laravel’s built-in logging system.

69