应用程序无响应 (ANR)
了解如何关闭或指定 Node.js 的 ANR
应用程序无响应 (ANR) 错误,或事件循环停滞错误,当应用程序的 Node.js 主线程事件循环被阻塞超过五秒时触发。Node SDK 将 ANR 错误报告为 Sentry 事件,并可以选择将阻塞代码的堆栈跟踪附加到 ANR 事件中。
此功能当前处于 Beta 阶段。Beta 功能仍在开发中,可能存在 bug。我们意识到其中的讽刺意味。
ANR 检测不支持 Node.js 集群。
(自版本 7.91.0 及以上可用)
要启用 ANR 检测,请从 @sentry/node
包中添加 Anr
集成。
ANR 检测需要 Node 16 或更高版本,并且只能在 Node.js 运行时中使用。
Copied
Sentry.init({
dsn: "https://examplePublicKey@o0.ingest.sentry.io/0",
integrations: [Sentry.anrIntegration({ captureStackTrace: true })],
});
您可以传递一个配置对象给 Anr
集成,以自定义 ANR 检测行为。
Copied
interface Options {
/**
* Interval to send heartbeat messages to the ANR thread.
*
* Defaults to 50ms.
*/
pollInterval: number;
/**
* Threshold in milliseconds to trigger an ANR event.
*
* Defaults to 5000ms.
*/
anrThreshold: number;
/**
* Whether to capture a stack trace when the ANR event is triggered.
*
* Defaults to `false`.
*
* This uses the node debugger which enables the inspector API.
*/
captureStackTrace: boolean;
}
Node SDK 使用工作线程(worker thread)来监控主线程中的事件循环以检测 ANR。主线程每 50 毫秒向 ANR 工作线程发送一次心跳消息。如果 ANR 工作线程在 5 秒内未收到心跳消息,它将触发一个 ANR 事件。如果启用了 captureStackTrace
选项,ANR 工作线程将使用 inspector
模块通过 v8 调试器 API 捕获堆栈跟踪。
一旦报告了 ANR 事件,ANR 工作线程将退出以防止进一步的重复事件,而主线程将继续正常运行。
Node.js ANR 跟踪的开销应非常小。在没有检测到 ANR 的情况下,主线程中唯一的开销是默认每 50 毫秒通过 IPC 轮询 ANR 工作线程。ANR 工作线程大约消耗 10-20 MB 的 RAM 来跟踪轮询。一旦检测到 ANR,主线程将在调试器中短暂暂停以捕获堆栈跟踪帧。此时,事件循环已经被阻塞了几秒钟,因此调试开销可以忽略不计。