Laravel Logs to Sentry

If text-based logging is all you have, you should give a try to Sentry. It’s an amazing way to visualize and get notified about exceptions. And it supports a bunch of languages and frameworks. You can find more on its website, now I want to share a small tip to having your Laravel log outputted to Sentry.

When you set up Sentry to work with Laravel based on their guide, only exceptions will be sent to Sentry. If you have something like this:

try {
    throw new \Exception('Foo');
} catch (\Exception $e) {
    \Log::error($e);
}

That exception won’t reach the handler. So, Sentry won’t receive it.

There are a couple ways to forward that exception to Sentry, though. One of them is by doing the following:

try {
    throw new \Exception('Foo');
} catch (\Exception $e) {
    \Log::error($e);
    app('sentry')->captureException($e);
}

Yet, if you already wrote a lot of code, seeking for all your logging calls and adding that line can be a pain. To avoid that it’s possible to listen to the log event. Add a listener to your EventServiceProvider:

public function boot()
{
    parent::boot();
    Event::listen('illuminate.log', function ($level, $message, $context) {
        $sentry = app('sentry');
        if ($message instanceof \Exception) {
            $sentry->captureException($message, $context);
        } else {
            $sentry->captureMessage($message, null, $context);
        }
    });
}

This way all you’re logging calls will go to Sentry. You may found that some debug logging, for instance, may be pulled out from this logic. Add a condition to prevent it:

Event::listen('illuminate.log', function ($level, $message, $context) {
    if (in_array($level, [ 'debug', 'info' ])) {
        return;
    }

    // ...

});

BTW, Happy new year! ;)

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s