自定义集成
了解如何启用自定义集成。
除了 SDK 自带的集成外,你还可以编写自定义集成。
自定义集成必须符合 Integration 接口。
可以如下创建并添加自定义集成到 SDK:
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 初始化时被调用。它接收客户端实例作为参数。 如果你希望在初始化时运行一些代码,应该使用此钩子。
const integration = {
name: "MyAwesomeIntegration",
setup(client) {
setupCustomSentryListener(client);
},
};
此钩子可用于在事件发送到 Sentry 之前修改事件。它接收事件作为参数,并应返回修改后的事件。钩子还接收一个可能包含额外事件元数据的 hint 对象,以及发送事件的客户端。你也可以返回 null
以阻止事件被发送。
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
,此钩子接收事件、hint 和客户端。
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()
并且你想确保某段代码只运行一次时。
const integration = {
name: "MyAwesomeIntegration",
setupOnce() {
wrapLibrary();
},
};
虽然我们建议在大多数情况下使用 setup
钩子,但 afterAllSetup
可以用于确保所有其他集成已经运行。此钩子接收正在设置的 client
作为第一个参数,并在所有集成的 setupOnce()
和 setup()
被调用之后触发。
const integration = {
name: "MyAwesomeIntegration",
afterAllSetup(client) {
// We can be sure that all other integrations
// have run their `setup` and `setupOnce` hooks now
startSomeThing(client);
},
};