Matt Komarnicki
Matt Komarnicki

Reputation: 5422

Laravel and Sentry: How to set a custom tag in Sentry?

In my Laravel's middleware I generate a custom header value.

$correlationId = Uuid::uuid4()->toString();

if ($request->headers->has('Correlation-ID') === false) {
    $request->headers->set('Correlation-ID', $correlationId);
}

When I throw an exception I easily get it in Sentry along with my custom header.

enter image description here

But the power of using Sentry and Correlation Id is when you tag something, each tagged value is indexed hence it amplifies the search feature to track issues.

I've found a logic for adding tags:

\Sentry\configureScope(function (\Sentry\State\Scope $scope): void {
    $scope->setTag('correlation_id', app(\Illuminate\Http\Request::class)->headers->get('Correlation-ID'));
});

The problem is that I don't know where to put it. When I add it into the same middleware it doesn't push my new correlation_id tag into sentry. Same when I put this code into boot method in AppServiceProvider class in a destination micro-service.

I can confirm that I get the UUID with no problems app(\Illuminate\Http\Request::class)->headers->get('Correlation-ID') but Sentry displays only the build-in tags:

enter image description here

What am I doing wrong?

Upvotes: 2

Views: 3946

Answers (2)

user2664585
user2664585

Reputation: 21

I'd recommend adding tags via a middleware;

public function handle($request, Closure $next)
{
    app('sentry')->configureScope(
        function (Scope $scope){
            $scope->setTag('my_tag_name', 'my_tag_value');
        }
    );
    return $next($request);
}

I've tried adding tags in Handler.php but without any success.

Upvotes: 0

Matt Komarnicki
Matt Komarnicki

Reputation: 5422

OK, I have found the answer by myself.

The Handler class in App\Exceptions is the correct place.

/**
 * Report or log an exception.
 *
 * This is a great spot to send exceptions to Sentry, Bugsnag, etc.
 *
 * @param  \Exception  $exception
 * @return void
 */
public function report(Exception $e)
{
    if (app()->bound('sentry') && $this->shouldReport($e)) {
        app('sentry')->withScope(function (\Sentry\State\Scope $scope) use ($e): void {
            $scope->setTag('correlation_id', app(\Illuminate\Http\Request::class)->headers->get('Correlation-ID'));

            app('sentry')->captureException($e);
        });
    }

    parent::report($e);
}

Caught issue on Sentry looks like:

enter image description here

Upvotes: 4

Related Questions