过滤

了解如何配置您的 SDK 以过滤报告给 Sentry 的事件。

当您将 Sentry 添加到您的应用程序时,会获得大量关于错误和性能的有价值信息。大量的信息是好的——只要它是正确且适量的信息。

Sentry 提供了 入站过滤器,您可以为每个项目启用这些过滤器以在 sentry.io 中过滤各种事件。您可以使用我们预定义的入站过滤器(例如,过滤已知的浏览器扩展),也可以添加自己的基于消息的过滤器。

然而,我们建议在客户端级别进行过滤,因为这可以避免发送不需要的事件所带来的开销。Sentry SDK 提供了几种配置选项,本文档中对此进行了描述,以帮助您过滤事件。要了解更多可用于过滤的事件字段,请参阅 事件有效负载

通过使用 beforeSend 回调方法以及配置、启用或禁用集成,您可以配置 SDK 以过滤错误事件。

您可以使用 ignoreErrors 选项来过滤与特定模式匹配的错误。此选项接收一个字符串和正则表达式的列表,用于匹配错误消息。当使用字符串时,部分匹配的错误将被过滤掉。如果您需要进行精确匹配,请改用正则表达式模式。

Copied
Sentry.init({
  dsn: "https://examplePublicKey@o0.ingest.sentry.io/0",
  ignoreErrors: ["fb_xd_fragment", /^Exact Match Message$/],
});

您可以配置一个 beforeSend 回调方法来过滤错误事件。由于它在事件发送到服务器之前立即被调用,因此这是您决定是否不发送数据或编辑数据的最后机会。beforeSend 接收事件对象作为参数,并根据自定义逻辑和事件中的可用数据,您可以修改事件的数据或通过返回 null 完全丢弃该事件。

在 JavaScript 中,您可以使用一个函数来修改事件或返回一个全新的事件。 您可以返回 null 或事件有效负载——不允许返回其他任何值(包括 void)。 如果您返回 null,该事件将被丢弃。

Copied
Sentry.init({
  dsn: "https://examplePublicKey@o0.ingest.sentry.io/0",

  // Called for message and error events
  beforeSend(event) {
    // Modify or drop the event here
    if (event.user) {
      // Don't send user's email address
      delete event.user.email;
    }
    return event;
  },
});

另外需要注意的是,面包屑(breadcrumbs)也可以被过滤,具体请参阅 我们的 Breadcrumbs 文档

beforeSend 回调不仅接收 event,还接收第二个参数 hint,其中包含一个或多个提示。

通常,hint 包含原始异常,以便从中提取额外数据或影响分组。在以下示例中,如果捕获了特定类型的异常,则强制指纹设置为一个通用值:

Copied
Sentry.init({
  // ...
  beforeSend(event, hint) {
    const error = hint.originalException;
    if (
      error &&
      error.message &&
      error.message.match(/database unavailable/i)
    ) {
      event.fingerprint = ["database-unavailable"];
    }
    return event;
  },
});

有关可用提示的更多信息,请参阅 JavaScript 中的提示

当 SDK 创建事件或面包屑以进行传输时,这些传输通常是基于某种源对象创建的。例如,错误事件通常是基于日志记录或异常实例创建的。为了更好的自定义,SDK 会将这些对象传递给某些回调(如 beforeSendbeforeBreadcrumb 或 SDK 中的事件处理器系统)。

提示在两个地方可用:

  1. beforeSend / beforeBreadcrumb
  2. eventProcessors

事件和面包屑的 hints 是包含各种信息的对象,用于组装事件或面包屑。通常,hints 包含原始异常,以便从中提取额外数据或影响分组。

对于事件,hints 包含以下属性:

  • event_id
  • originalException
  • syntheticException(用于生成更清晰的堆栈跟踪,内部使用)
  • 任意附加的 data

对于面包屑,hints 的使用取决于具体实现。例如:

  • 对于 XHR 请求,hint 包含 xhr 对象本身;
  • 对于用户交互,hint 包含 DOM 元素和事件名称等。
Copied
Sentry.init({
  // ...
  beforeSend(event, hint) {
    const error = hint.originalException;
    if (
      error &&
      error.message &&
      error.message.match(/database unavailable/i)
    ) {
      event.fingerprint = ["database-unavailable"];
    }
    return event;
  },
});

originalException

导致 Sentry SDK 创建事件的原始异常。这对于更改 Sentry SDK 如何分组事件或提取额外信息非常有用。

syntheticException

当抛出字符串或非错误对象时,Sentry 会创建一个合成异常以获取基本的堆栈跟踪。此异常存储在此处,以便进一步提取数据。

level / input

For breadcrumbs created from console log interceptions. This holds the original console log level and the original input data to the log function.

request / response / event

For breadcrumbs created from HTTP requests. This holds the request and response object (from the node HTTP API) as well as the node event (response or error).

您可以构建一个错误的允许域名列表。只有在这些域内创建的错误才会被捕获。例如,如果您的脚本是从 cdn.example.com 加载的,而您的网站是 example.com,您可以将 allowUrls 设置为:

Copied
Sentry.init({
  allowUrls: [/https?:\/\/((cdn|www)\.)?example\.com/],
});

如果您希望阻止特定 URL 上创建的错误被发送到 Sentry,也可以使用 denyUrls

适用于从版本 8.10.0 开始的基于浏览器的 SDK

thirdPartyErrorFilterIntegration 允许您过滤来自第三方的错误,例如浏览器扩展、注入代码的浏览器或也使用 Sentry 的第三方服务的小部件。此集成可以帮助减少与您自己的应用程序代码无关的噪声。

前提条件:要使用 thirdPartyErrorFilterIntegration,请确保您正在使用打包工具和 Sentry 的打包工具插件之一。

此集成通过在构建过程中用“应用程序密钥”标记您的 JavaScript 文件来工作。运行时,如果发生错误,此集成会检查堆栈跟踪中每个堆栈帧的应用程序密钥。这使您可以过滤掉带有“未标记”堆栈帧的错误,这些错误通常表示第三方代码。

要设置此集成并用应用程序密钥标记您的 JavaScript 文件,请首先将 applicationKey 选项传递给您的 Sentry 打包工具插件。这可以是任意字符串,用于标识您的应用程序代码:

Copied
// vite.config.ts
import { defineConfig } from "vite";
import { sentryVitePlugin } from "@sentry/vite-plugin";

export default defineConfig({
  plugins: [
    sentryVitePlugin({
      applicationKey: "your-custom-application-key",
    }),
  ],
});

接下来,在您的 Sentry 初始化中添加 thirdPartyErrorFilterIntegration

Copied
Sentry.init({
  integrations: [
    Sentry.thirdPartyErrorFilterIntegration({
      // Specify the application keys that you specified in the Sentry bundler plugin
      filterKeys: ["your-custom-application-key"],

      // Defines how to handle errors that contain third party stack frames.
      // Possible values are:
      // - 'drop-error-if-contains-third-party-frames'
      // - 'drop-error-if-exclusively-contains-third-party-frames'
      // - 'apply-tag-if-contains-third-party-frames'
      // - 'apply-tag-if-exclusively-contains-third-party-frames'
      behaviour: "drop-error-if-contains-third-party-frames",
    }),
  ],
});

filterKeys 选项接收一个字符串数组,这些字符串应与打包工具插件选项中设置的 applicationKey 值相匹配。除非您的网站托管了来自多个构建过程的文件,否则该数组应仅包含一个项。

behaviour 选项定义了如何处理包含第三方代码堆栈帧的错误。您可以选择四种模式:

  • "drop-error-if-contains-third-party-frames":丢弃包含至少一个第三方堆栈帧的错误事件。
  • "drop-error-if-exclusively-contains-third-party-frames":丢弃仅包含第三方堆栈帧的错误事件。
  • "apply-tag-if-contains-third-party-frames":保留所有错误事件,但如果错误包含至少一个第三方堆栈帧,则应用 third_party_code: true 标签。
  • "apply-tag-if-exclusively-contains-third-party-frames":保留所有错误事件,但如果错误仅包含第三方堆栈帧,则应用 third_party_code: true 标签。

如果您选择仅应用标签的模式,这些标签可以在 Sentry 中用于通过 third_party_code 标签在问题搜索栏中过滤您的问题流。

thirdPartyErrorFilterIntegration 不适用于 Sentry Loader Script 或 CDN Bundles。这是因为 Sentry Loader Script 和 CDN Bundles 被该集成检测为“第三方”。这会导致几乎所有的事件都应用所选的行为,因为 Sentry SDK 包装了许多浏览器原生的 API。

要防止某些事务被报告给 Sentry,可以使用 tracesSampler 或 beforeSendTransaction 配置选项,这些选项允许您提供一个函数来评估当前事务并在不需要时丢弃它。

您可以使用 ignoreTransactions 选项来过滤与特定模式匹配的事务。此选项接收一个字符串和正则表达式的列表,用于匹配事务名称。当使用字符串时,部分匹配的事务将被过滤掉。如果您需要进行精确匹配,请改用正则表达式模式。

Copied
Sentry.init({
  dsn: "https://examplePublicKey@o0.ingest.sentry.io/0",
  ignoreTransactions: ["partial/match", /^Exact Transaction Name$/],
});

注意: tracesSampler 和 tracesSampleRate 配置选项是互斥的。如果您定义了一个 tracesSampler 来过滤某些事务,则还必须处理未过滤事务的情况,通过返回您希望采样的比率。

最简单的形式,仅用于过滤事务时,它看起来像这样:

Copied
// The shape of samplingContext that is passed to the tracesSampler function
interface SamplingContext {
  // Name of the span
  name: string;
  // Initial attributes of the span
  attributes: SpanAttributes | undefined;
  // If the parent span was sampled - undefined if there is no parent span
  parentSampled: boolean | undefined;
}

Sentry.init({
  // ...

  tracesSampler: ({ name, attributes, parentSampled }) => {
    // Do not sample health checks ever
    if (name.includes("healthcheck")) {
      // Drop this transaction, by setting its sample rate to 0%
      return 0;
    }

    // Continue trace decision, if there is any parentSampled information
    if (typeof parentSampled === "boolean") {
      return parentSampled;
    }

    // Else, use default sample rate (replacing tracesSampleRate)
    return 0.5;
  },
});

它还允许您以不同的速率对不同的事务进行采样。

如果当前正在处理的事务有一个父事务(来自上游服务调用此服务),父(上游)采样决策将始终包含在采样上下文数据中,因此您的 tracesSampler 可以选择是否以及何时继承该决策。在大多数情况下,继承是正确的选择,以避免破坏分布式跟踪。断裂的跟踪将不会包含所有您的服务。更多详情请参阅 继承父级采样决策

了解更多关于 配置采样率 的信息。

Copied
Sentry.init({
  dsn: "https://examplePublicKey@o0.ingest.sentry.io/0",

  // Called for transaction events
  beforeSendTransaction(event) {
    // Modify or drop the event here
    if (event.transaction === "/unimportant/route") {
      // Don't send the event to Sentry
      return null;
    }
    return event;
  },
});

自 Javascript SDK 版本 8.2.0 起可用。

要防止某些跨度被报告给 Sentry,可以使用 beforeSendSpan 配置选项,该选项允许您提供一个函数来修改和丢弃子跨度。此函数仅对根跨度的子跨度调用。如果您想修改或丢弃根跨度及其子跨度,请使用 beforeSendTransaction

Copied
Sentry.init({
  dsn: "https://examplePublicKey@o0.ingest.sentry.io/0",

  // Called for spans
  beforeSendSpan(span) {
    // Modify or drop the span here
    if (span.description === "unimportant span") {
      // Don't send the span to Sentry
      return null;
    }
    return span;
  },
});