Late Initialization (ESM or CJS)

了解如何在 ESM 或 CJS 应用程序中运行 Sentry,特别是在无法尽早初始化的情况下。

为了使自动仪器化正常工作,通常需要尽可能早地运行 Sentry.init(),在应用程序中导入任何其他内容之前。

然而,在某些情况下这可能是不可能的——例如,如果你从外部源获取 DSN。在这种情况下,你可以使用 @sentry/node/preload 钩子来确保模块尽早被包装,从而允许你稍后在你选择的时间调用 Sentry.init()

我们建议仅在绝对必要时使用此方法。在大多数情况下,最好找到一种方法在应用程序早期运行 Sentry.init(),以确保没有错误未被报告。

此初始化方法从版本 8.5.0 开始可用。

在你的 CJS 应用程序中,使用 @sentry/node/preload 钩子和 --require 以确保模块尽早被包装:

Copied
node --require @sentry/node/preload app.js

然后,在你的应用程序中你可以在稍后的某个点调用 Sentry.init()

main.js
Copied
const startApp = require("./app");
const fetchDsn = require("./utils/fetchDsn");
const Sentry = require("@sentry/node");

startApp();

const dsn = fetchDsn();
Sentry.init({
  dsn,

  // Add Tracing by setting tracesSampleRate
  // We recommend adjusting this value in production
  tracesSampleRate: 1.0,
});

// From now on, Sentry is initialized,
// but the app is still auto-instrumented

在你的 ESM 应用程序中,使用 @sentry/node/preload 钩子和 --import 以确保模块尽早被包装:

Copied
# Note: This is only available for Node v18.19.0 onwards.
node --import @sentry/node/preload app.js

然后,在你的应用程序中你可以在稍后的某个点调用 Sentry.init()

main.js
Copied
import startApp from "./app";
import fetchDsn from "./utils/fetchDsn";
import * as Sentry from "@sentry/node";

startApp();

const dsn = fetchDsn();
Sentry.init({
  dsn,

  // Add Tracing by setting tracesSampleRate
  // We recommend adjusting this value in production
  tracesSampleRate: 1.0,
});

// From now on, Sentry is initialized,
// but the app is still auto-instrumented

预加载的集成确保必要的模块在应用程序导入它们之前被包装。此时,模块已被包装,但不会执行任何操作——不会从它们发出或捕获任何数据。

一旦你调用 Sentry.init(),被包装的模块将自动开始发出性能数据并将其发送到 Sentry。

默认情况下,使用 @sentry/node/preload 钩子时,所有性能仪器化都会被预加载。

你可以选择性地配置仅预加载某些集成,通过定义 SENTRY_PRELOAD_INTEGRATIONS 环境变量。此变量应包含要预加载的集成名称,例如:

Copied
SENTRY_PRELOAD_INTEGRATIONS="Http,Express" node --require @sentry/node/preload app.js

你可以传递以下任何集成的名称:

  • Http
  • Express
  • Connect
  • Fastify
  • Hapi
  • Koa
  • Nest
  • Mongo
  • Mongoose
  • Mysql
  • Mysql2
  • Postgres
  • Graphql

请注意,不需要预加载 NodeFetch,它将始终被仪器化。

你还可以定义 SENTRY_DEBUG 环境变量以从预加载钩子获取调试日志。这有助于理解预加载过程中的情况。

Copied
SENTRY_DEBUG=1 node --require @sentry/node/preload app.js