首页 > 解决方案 > Laravel 和 Sentry:如何在 Sentry 中设置自定义标签?

问题描述

在我的 Laravel 中,middleware我生成了一个自定义标头值。

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

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

当我抛出异常时,我很容易在 Sentry 中得到它以及我的自定义标头。

在此处输入图像描述

但是使用 Sentry 和 Correlation Id 的强大之处在于,当您标记某些内容时,每个标记的值都会被编入索引,因此它会放大搜索功能以跟踪问题。

我找到了添加标签的逻辑:

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

问题是我不知道把它放在哪里。当我将它添加到同一个中间件时,它不会将我的新correlation_id标签推送到哨兵中。当我将此代码放入目标微服务boot的类中的方法时也是如此。AppServiceProvider

我可以确认我没有问题地获得 UUID,app(\Illuminate\Http\Request::class)->headers->get('Correlation-ID')但 Sentry 仅显示内置标签:

在此处输入图像描述

我究竟做错了什么?

标签: phplaravelphp-7sentry

解决方案


好的,我自己找到了答案。

中的Handler班级App\Exceptions是正确的地方。

/**
 * 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);
}

在 Sentry 上捕获的问题如下所示:

在此处输入图像描述


推荐阅读