【问题标题】:Laravel and Sentry: How to set a custom tag in Sentry?Laravel 和 Sentry:如何在 Sentry 中设置自定义标签?
【发布时间】:2021-01-13 22:44:05
【问题描述】:

在我的 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 标签推送到哨兵中。当我将此代码放入目标微服务中AppServiceProvider 类中的boot 方法时也是如此。

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

我做错了什么?

【问题讨论】:

    标签: php laravel php-7 sentry


    【解决方案1】:

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

    App\Exceptions 中的 Handler 类是正确的位置。

    /**
     * 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 上发现的问题如下所示:

    【讨论】:

      【解决方案2】:

      我建议通过中间件添加标签;

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

      我尝试在Handler.php 中添加标签,但没有任何成功。

      【讨论】:

        猜你喜欢
        • 2018-04-11
        • 2020-01-01
        • 1970-01-01
        • 2018-10-24
        • 1970-01-01
        • 2013-08-03
        • 2020-06-24
        • 2021-01-05
        • 1970-01-01
        相关资源
        最近更新 更多