Usage

Sentry's SDK hooks into your runtime environment and automatically reports errors, exceptions, and rejections.

The most common form of capturing is to capture errors. What can be captured as an error varies by platform. In general, if you have something that looks like an exception it can be captured. For some SDKs you can also omit the argument to capture_exception and Sentry will attempt to capture the current exception. It can also be useful to manually report errors or messages to Sentry.

Separately to capturing you can also record the breadcrumbs that lead up to an event. Breadcrumbs are different from events: they will not create an event in Sentry, but will be buffered until the next event is sent. Learn more about breadcrumbs in our Breadcrumbs documentation.

Capturing Errors

In Laravel, you can pass an error object to captureException() to get it captured as an event. It’s also possible to throw strings as errors, in which case no traceback can be recorded.

In PHP you can either capture a caught exception or capture the last error with captureLastError.

Copied
try {
    $this->functionFailsForSure();
} catch (\Throwable $exception) {
    \Sentry\captureException($exception);
}

Capturing Messages

Another common operation is to capture a bare message. A message is textual information that should be sent to Sentry. Typically messages are not emitted, but they can be useful for some teams.

Copied
\Sentry\captureMessage('Something went wrong');

Customization

Decorating the Client Builder

Starting with version 1.5.0 of sentry-laravel you can customize how the PHP SDK client is built by modifying the client builder.

You might want to do this to, for example, replace the transport or change the serializer options used, which can only be changed when building the client.

The snippet below must be placed in the register method of a service provider (for example your AppServiceProvider).

In this example we increase maxDepth to 5 in for the default serializer.

Copied
use Sentry\Serializer\Serializer;
use Sentry\ClientBuilderInterface;

$this->app->extend(ClientBuilderInterface::class, function (ClientBuilderInterface $clientBuilder) {
    $clientBuilder->setSerializer(new Serializer($clientBuilder->getOptions(), 5));

    return $clientBuilder;
});

User Context

Starting with Laravel 5.3 we can automatically add the authenticated user id to the scope if send_default_pii option is set to true in your config/sentry.php.

The mechanism to add more user context to the scope will vary depending on which version of Laravel you're using, but the general approach is the same. Find a good entry point to your application in which the context you want to add is available, ideally early in the process.

In the following example, we'll use a middleware to add the user information if a user is logged in:

Copied
namespace App\Http\Middleware;

use Closure;
use Sentry\State\Scope;

class SentryContext
{
    /**
     * Handle an incoming request.
     *
     * @param \Illuminate\Http\Request $request
     * @param \Closure                 $next
     *
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        if (auth()->check() && app()->bound('sentry')) {
            \Sentry\configureScope(function (Scope $scope): void {
                $scope->setUser([
                    'id' => auth()->user()->id,
                    'email' => auth()->user()->email,
                ]);
            });
        }

        return $next($request);
    }
}

Log Channels

Starting with Laravel & Lumen 5.6 we can setup Sentry using log channels.

To configure Sentry as a log channel, add the following config to the channels section in config/logging.php:

config/logging.php
Copied
'channels' => [
    // ...
    'sentry' => [
        'driver' => 'sentry',
    ],
],

After you configured the Sentry log channel, you can configure your app to both log to a log file and to Sentry by modifying the log stack:

config/logging.php
Copied
'channels' => [
    'stack' => [
        'driver' => 'stack',
        // Add the Sentry log channel to the stack
        'channels' => ['single', 'sentry'],
    ],
    //...
],

Optionally, you can set the logging level and if events should bubble on the driver:

config/logging.php
Copied
'channels' => [
    // ...
    'sentry' => [
        'driver' => 'sentry',
        // The minimum logging level at which this handler will be triggered
        // Available levels: debug, info, notice, warning, error, critical, alert, emergency
        'level' => env('LOG_LEVEL', 'error'), 
        'bubble' => true, // Whether the messages that are handled can bubble up the stack or not
    ],
],

Queue Jobs

When you have defined a failed method on your job class (documentation), that failed method acts as if your job runs inside a try {} catch (\Exception $e) {}. This will prevent reporting exception, causing the job to have failed to be reported to Sentry.

This could be expected since your job sometimes fails due to an API that is not reachable or other expected failures. If you still want the exception to be reported to Sentry, you can implement the following in your failed method:

Copied
/**
 * The job failed to process.
 *
 * @param \Exception $exception
 *
 * @return void
 */
public function failed(\Exception $exception)
{
    // Send user notification of failure, etc...

    if (app()->bound('sentry')) {
        app('sentry')->captureException($exception);
    }
}

Naming Your Log Channels

To filter on multiple log channels inside Sentry, you can add the name attribute to the log channel. It will show up in Sentry as the logger tag, which is filterable.

For example:

config/logging.php
Copied
'channels' => [
    'my_stacked_channel' => [
        'driver' => 'stack',
        'channels' => ['single', 'sentry'],
        'name' => 'my-channel'
    ],
    //...
],

As a result, you can log errors to your channel:

Copied
\Log::channel('my_stacked_channel')->error('My error');

And Sentry's logger tag now has the channel's name. You can filter on the "my-channel" value.

Resolve Name Conflicts

If you have other packages also named Sentry, you'll need to create your own service provider extending ours so we can prevent naming conflicts.

Copied
<?php

namespace App\Support;

class SentryLaravelServiceProvider extends \Sentry\Laravel\ServiceProvider
{
    public static $abstract = 'sentry-laravel';
}

You can then add this service provider to the config/app.php.

config/app.php
Copied
'providers' => array(
    // ...
    App\Support\SentryLaravelServiceProvider::class,
)

Optionally, if you want to use the facade, you also need to extend/create a new facade.

Copied
<?php

namespace App\Support;

class SentryLaravelFacade extends \Sentry\Laravel\Facade
{
    protected static function getFacadeAccessor()
    {
        return 'sentry-laravel';
    }
}

And add that facade to your config/app.php.

config/app.php
Copied
'aliases' => array(
    // ...
    'SentryLaravel' => App\Support\SentryLaravelFacade::class,
)

After you've added your own service provider, running php artisan vendor:publish --provider="App\Support\SentryLaravelServiceProvider" publishes the Sentry config file to your chosen name (in the example above config/sentry-laravel.php) preventing conflicts with a config/sentry.php config file that might be used by the other package.

If you followed the regular installation instructions above (you should), make sure you replace app('sentry') with app('sentry-laravel').

The namespace \App\Support can be anything you want in the examples above.

composer.json
Copied
"extra": {
    "laravel": {
        "dont-discover": ["sentry/sentry-laravel"]
    }
}