php - 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 仅显示内置标签:
我究竟做错了什么?
解决方案
好的,我自己找到了答案。
中的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 上捕获的问题如下所示:
推荐阅读
- android - 在 FAB 单击时导航到片段(导航架构组件)
- linux - Prevent removal of busy kernel module
- vba - Check if Date is 2 months prior to today's date
- python - 使用 python 解析嵌套的 XML
- python - How to use a range variable in a list without raising a SyntaxError?
- java - 如何使用 Apache POI 基于外部数据创建数据透视表?
- javascript - Sequelize 语法错误 (N\')
- reporting-services - SSRS add group to existing rdl file
- api - API authtentication with a Ionic app
- java - 可以将 Afterburner.fx 注入到非演示者类中吗?