SDK 指纹识别

了解如何在 SDK 中覆盖默认的指纹识别。

所有事件都有一个指纹。具有相同指纹的事件会被归类为一个问题。

默认情况下,Sentry 会运行我们内置的分组算法之一,根据事件中的信息(如 stacktraceexceptionmessage)生成指纹。要扩展默认的分组行为或完全更改它,您可以使用以下选项的组合:

  1. 在您的 SDK 中使用 SDK 指纹识别,如下文所述
  2. 在您的项目中使用 指纹规则堆栈跟踪规则

在支持的 SDK 中,您可以通过传递指纹属性作为字符串数组来覆盖 Sentry 的默认分组行为。指纹数组的长度没有限制。这与始终可用的 指纹规则功能 类似,可以实现类似的结果。

在最简单的情况下,值直接传递:

Copied
try {
    // Run code that possibly throws an exception
} catch (\Throwable $e) {
    \Sentry\withScope(function (\Sentry\State\Scope $scope) use ($e) {
        $scope->setFingerprint(['example-exception-group']);
        \Sentry\captureException($e);
    });
}

您可以使用变量替换将动态值填充到通常在服务器端计算的指纹中。例如,可以添加值 {{ default }} 以将整个正常生成的分组哈希添加到指纹中。这些值与服务器端指纹识别中的值相同。更多信息请参阅 变量

在某些情况下,您希望更细致地分组错误。

例如,如果您的应用程序查询远程过程调用模型(RPC)接口或外部应用程序编程接口(API)服务,即使传出的请求非常不同,堆栈跟踪通常也是相同的。

以下示例将在 Sentry 创建的默认分组(由 {{ default }} 表示)基础上进一步细分,考虑错误对象的某些属性:

Copied
class MyRpcException extends \Exception
{
    private string $functionName;
    private int    $statusCode;

    /**
     * For example the name of the RPC function that was called (e.g. "getAllBlogArticles").
     */
    public function getFunctionName(): string
    {
        return $this->functionName;
    }

    /**
     * For example a HTTP status code returned by the server.
     */
    public function getStatusCode(): int
    {
        return $this->statusCode;
    }
}

try {
    // Run code that for example throws a MyRpcException
} catch (MyRpcException $e) {
    \Sentry\withScope(function (\Sentry\State\Scope $scope) use ($e) {
        $scope->setFingerprint([
          '{{ default }}',
          $e->getFunctionName(),
          $e->getStatusCode(),
        ]);
        \Sentry\captureException($e);
    });
}

您也可以完全覆盖 Sentry 的分组行为。

例如,对于数据库连接错误等通用错误,可能有多个不同的堆栈跟踪且从不归为同一组。您可以通过从数组中省略 {{ default }} 来覆盖 Sentry 的分组行为:

Copied
try {
    // Run code that for example throws a PDOException
} catch (\PDOException $e) {
    \Sentry\withScope(function (\Sentry\State\Scope $scope) use ($e) {
        $scope->setFingerprint(['database-connection-error']);
        \Sentry\captureException($e);
    });
}