Custom Integrations

了解如何启用自定义集成。

除了 SDK 自带的集成外,您还可以编写自定义集成。

自定义集成必须符合 Integration 接口

可以按照以下方式创建并添加自定义集成到 SDK:

Copied
function myAwesomeIntegration() {
  return {
    name: "MyAwesomeIntegration",
    setup(client) {
      // Do something when the SDK is initialized
      // The client that is being setup is passed to the hook
    },
  };
}

Sentry.init({
  // ...
  integrations: [myAwesomeIntegration()],
});

集成上的所有钩子都是可选的。唯一必需的字段是 name。您可以在自定义集成中使用以下一个或多个钩子:

setup 钩子在 SDK 初始化时被调用。它接收客户端实例作为参数。 如果您希望在初始化时运行某些代码,应该使用此钩子。

Copied
const integration = {
  name: "MyAwesomeIntegration",
  setup(client) {
    setupCustomSentryListener(client);
  },
};

此钩子可用于在事件发送到 Sentry 之前修改事件。它接收事件作为参数,并应返回修改后的事件。钩子还接收一个可能包含额外事件元数据的提示对象,以及发送事件的客户端。您也可以返回 null 以阻止事件被发送。

Copied
const integration = {
  name: "MyAwesomeIntegration",
  processEvent(event, hint, client) {
    event.extra = {
      ...event.extra,
      myCustomTag: "value",
    };
    // Return the modified event,
    // or return `null` to drop the event
    return event;
  },
};

您也可以返回一个以事件或 null 解析的 Promise。然而,这并不推荐,应尽可能避免,因为它可能会延迟事件的发送。

此钩子与 processEvent 类似,但它在事件传递给任何其他 processEvent 钩子之前被调用。它可以在需要确保处理顺序的地方使用。

在大多数情况下,您应该直接使用 processEvent。只有当您需要确保您的钩子在所有其他 processEvent 钩子之前被调用时,才使用 preprocessEvent

类似于 processEvent,此钩子接收事件、提示和客户端作为参数。但是,此钩子不允许返回修改后的事件或 null 来阻止事件发送——相反,您只能在此钩子中修改传入的事件:

Copied
const integration = {
  name: "MyAwesomeIntegration",
  preprocessEvent(event, hint, client) {
    event.extra = {
      ...event.extra,
      myCustomTag: "value",
    };
    // Nothing to return, just mutate the event
  },
};

此钩子与 setup 类似,但它只运行一次,即使 SDK 重新初始化也不会再次运行。它不接收任何参数。

您应该尽量避免使用此钩子,而是使用 setup。使用 setupOnce 的唯一原因是,例如,当您可能多次调用 Sentry.init() 并且希望确保某段代码只运行一次时。

Copied
const integration = {
  name: "MyAwesomeIntegration",
  setupOnce() {
    wrapLibrary();
  },
};

此钩子在所有集成的 setupOnce()setup() 被调用之后触发。如果需要确保所有其他集成已运行完毕,可以使用此钩子。

在大多数情况下,您不需要使用此钩子,而是应该使用 setup

该钩子接收正在设置的 client 作为第一个参数。

Copied
const integration = {
  name: "MyAwesomeIntegration",
  afterAllSetup(client) {
    // We can be sure that all other integrations
    // have run their `setup` and `setupOnce` hooks now
    startSomeThing(client);
  },
};