sentry-node-sdk
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseAll Skills > SDK Setup > Node.js / Bun / Deno SDK
所有技能 > SDK配置 > Node.js / Bun / Deno SDK
Sentry Node.js / Bun / Deno SDK
Sentry Node.js / Bun / Deno SDK
Opinionated wizard that scans your project and guides you through complete Sentry setup for server-side JavaScript and TypeScript runtimes: Node.js, Bun, and Deno.
这是一个预设配置的向导工具,会扫描你的项目并引导你完成服务器端JavaScript和TypeScript运行时(Node.js、Bun和Deno)的完整Sentry配置。
Invoke This Skill When
何时调用本技能
- User asks to "add Sentry to Node.js", "Bun", or "Deno"
- User wants to install or configure ,
@sentry/node, or@sentry/bun@sentry/deno - User wants error monitoring, tracing, logging, profiling, crons, metrics, or AI monitoring for a backend JS/TS app
- User asks about ,
instrument.js,--import ./instrument.mjs, orbun --preloadnpm:@sentry/deno - User wants to monitor Express, Fastify, Koa, Hapi, Connect, Bun.serve(), or Deno.serve()
NestJS? Useinstead — it usessentry-nestjs-sdkwith NestJS-native decorators and filters. Next.js? Use@sentry/nestjsinstead — it handles the three-runtime architecture (browser, server, edge).sentry-nextjs-sdk
Note: SDK versions below reflect current Sentry docs at time of writing (≥10.42.0,@sentry/node≥10.42.0,@sentry/bun≥10.42.0). Always verify against docs.sentry.io/platforms/javascript/guides/node/ before implementing.@sentry/deno
- 用户要求“为Node.js、Bun或Deno添加Sentry”
- 用户想要安装或配置、
@sentry/node或@sentry/bun@sentry/deno - 用户想要为后端JS/TS应用配置错误监控、链路追踪、日志记录、性能分析、任务调度、指标监控或AI监控
- 用户询问、
instrument.js、--import ./instrument.mjs或bun --preload相关内容npm:@sentry/deno - 用户想要监控Express、Fastify、Koa、Hapi、Connect、Bun.serve()或Deno.serve()
NestJS? 请改用—— 它使用sentry-nestjs-sdk,支持NestJS原生装饰器和过滤器。 Next.js? 请改用@sentry/nestjs—— 它适配三运行时架构(浏览器、服务器、边缘端)。sentry-nextjs-sdk
注意: 下文提到的SDK版本基于编写时的Sentry官方文档(≥10.42.0、@sentry/node≥10.42.0、@sentry/bun≥10.42.0)。 实施前请务必对照docs.sentry.io/platforms/javascript/guides/node/进行验证。@sentry/deno
Phase 1: Detect
阶段1:检测
Run these commands to identify the runtime, framework, and existing Sentry setup:
bash
undefined运行以下命令识别运行时、框架以及已有的Sentry配置:
bash
undefinedDetect runtime
检测运行时
bun --version 2>/dev/null && echo "Bun detected"
deno --version 2>/dev/null && echo "Deno detected"
node --version 2>/dev/null && echo "Node.js detected"
bun --version 2>/dev/null && echo "Bun detected"
deno --version 2>/dev/null && echo "Deno detected"
node --version 2>/dev/null && echo "Node.js detected"
Detect existing Sentry packages
检测已安装的Sentry包
cat package.json 2>/dev/null | grep -E '"@sentry/'
cat deno.json deno.jsonc 2>/dev/null | grep -i sentry
cat package.json 2>/dev/null | grep -E '"@sentry/'
cat deno.json deno.jsonc 2>/dev/null | grep -i sentry
Detect Node.js framework
检测Node.js框架
cat package.json 2>/dev/null | grep -E '"express"|"fastify"|"@hapi/hapi"|"koa"|"@nestjs/core"|"connect"'
cat package.json 2>/dev/null | grep -E '"express"|"fastify"|"@hapi/hapi"|"koa"|"@nestjs/core"|"connect"'
Detect Bun-specific frameworks
检测Bun专属框架
cat package.json 2>/dev/null | grep -E '"elysia"|"hono"'
cat package.json 2>/dev/null | grep -E '"elysia"|"hono"'
Detect Deno frameworks (deno.json imports)
检测Deno框架(deno.json中的导入)
cat deno.json deno.jsonc 2>/dev/null | grep -E '"oak"|"hono"|"fresh"'
cat deno.json deno.jsonc 2>/dev/null | grep -E '"oak"|"hono"|"fresh"'
Detect module system (Node.js)
检测模块系统(Node.js)
cat package.json 2>/dev/null | grep '"type"'
ls *.mjs *.cjs 2>/dev/null | head -5
cat package.json 2>/dev/null | grep '"type"'
ls *.mjs *.cjs 2>/dev/null | head -5
Detect existing instrument file
检测已有的instrument文件
ls instrument.js instrument.mjs instrument.ts instrument.cjs 2>/dev/null
ls instrument.js instrument.mjs instrument.ts instrument.cjs 2>/dev/null
Detect logging libraries
检测日志库
cat package.json 2>/dev/null | grep -E '"winston"|"pino"|"bunyan"'
cat package.json 2>/dev/null | grep -E '"winston"|"pino"|"bunyan"'
Detect cron / scheduling
检测任务调度工具
cat package.json 2>/dev/null | grep -E '"node-cron"|"cron"|"agenda"|"bull"|"bullmq"'
cat package.json 2>/dev/null | grep -E '"node-cron"|"cron"|"agenda"|"bull"|"bullmq"'
Detect AI / LLM usage
检测AI/LLM使用情况
cat package.json 2>/dev/null | grep -E '"openai"|"@anthropic-ai"|"@langchain"|"@vercel/ai"|"@google/generative-ai"'
cat package.json 2>/dev/null | grep -E '"openai"|"@anthropic-ai"|"@langchain"|"@vercel/ai"|"@google/generative-ai"'
Detect OpenTelemetry tracing
检测OpenTelemetry链路追踪
cat package.json 2>/dev/null | grep -E '"@opentelemetry/sdk-node"|"@opentelemetry/sdk-trace-node"|"@opentelemetry/sdk-trace-base"'
grep -rn "NodeTracerProvider|trace.getTracer|startActiveSpan"
--include=".ts" --include=".js" --include="*.mjs" 2>/dev/null | head -5
--include=".ts" --include=".js" --include="*.mjs" 2>/dev/null | head -5
cat package.json 2>/dev/null | grep -E '"@opentelemetry/sdk-node"|"@opentelemetry/sdk-trace-node"|"@opentelemetry/sdk-trace-base"'
grep -rn "NodeTracerProvider\|trace\.getTracer\|startActiveSpan" \
--include=".ts" --include=".js" --include="*.mjs" 2>/dev/null | head -5
Check for companion frontend
检查是否存在配套前端
ls frontend/ web/ client/ ui/ 2>/dev/null
cat package.json 2>/dev/null | grep -E '"react"|"vue"|"svelte"|"next"'
**What to determine:**
| Question | Impact |
|----------|--------|
| Which runtime? (Node.js / Bun / Deno) | Determines package, init pattern, and preload flag |
| Node.js: ESM or CJS? | ESM requires `--import ./instrument.mjs`; CJS uses `require("./instrument")` |
| Framework detected? | Determines which error handler to register |
| `@sentry/*` already installed? | Skip install, go straight to feature config |
| `instrument.js` / `instrument.mjs` already exists? | Merge into it rather than overwrite |
| Logging library detected? | Recommend Sentry Logs |
| Cron / job scheduler detected? | Recommend Crons monitoring |
| AI library detected? | Recommend AI Monitoring |
| OpenTelemetry tracing detected? | Use OTLP path instead of native tracing |
| Companion frontend found? | Trigger Phase 4 cross-link |
---ls frontend/ web/ client/ ui/ 2>/dev/null
cat package.json 2>/dev/null | grep -E '"react"|"vue"|"svelte"|"next"'
**需要确定的信息:**
| 问题 | 影响 |
|----------|--------|
| 使用哪种运行时?(Node.js / Bun / Deno) | 决定要安装的包、初始化方式以及预加载参数 |
| Node.js:使用ESM还是CJS? | ESM需要`--import ./instrument.mjs`;CJS使用`require("./instrument")` |
| 是否检测到框架? | 决定要注册的错误处理器 |
| 是否已安装`@sentry/*`包? | 跳过安装步骤,直接进入功能配置 |
| 是否已存在`instrument.js`/`instrument.mjs`? | 合并内容而非覆盖文件 |
| 是否检测到日志库? | 推荐使用Sentry Logs |
| 是否检测到任务调度工具? | 推荐使用任务调度监控 |
| 是否检测到AI库? | 推荐使用AI监控 |
| 是否检测到OpenTelemetry链路追踪? | 使用OTLP路径替代原生链路追踪 |
| 是否存在配套前端? | 触发阶段4的跨服务关联配置 |
---Phase 2: Recommend
阶段2:推荐
Present a concrete recommendation based on what you found. Don't ask open-ended questions — lead with a proposal:
Route from OTel detection:
- OTel tracing detected (or
@opentelemetry/sdk-nodein@opentelemetry/sdk-trace-node, orpackage.jsonin source) → use OTLP path:NodeTracerProviderviaotlpIntegration(); do not set@sentry/node-core/light; Sentry links errors to OTel traces automaticallytracesSampleRate
Recommended (core coverage):
- ✅ Error Monitoring — always; captures unhandled exceptions, promise rejections, and framework errors
- ✅ Tracing — automatic HTTP, DB, and queue instrumentation via OpenTelemetry
Optional (enhanced observability):
- ⚡ Logging — structured logs via ; recommend when
Sentry.logger.*/winston/pinoor log search is neededbunyan - ⚡ Profiling — continuous CPU profiling (Node.js only; not available on Bun or Deno); not available with OTLP path
- ⚡ AI Monitoring — OpenAI, Anthropic, LangChain, Vercel AI SDK; recommend when AI/LLM calls detected
- ⚡ Crons — detect missed or failed scheduled jobs; recommend when node-cron, Bull, or Agenda is detected
- ⚡ Metrics — custom counters, gauges, distributions; recommend when custom KPIs needed
- ⚡ Runtime Metrics — automatic collection of memory, CPU, and event loop metrics; (Node.js) /
nodeRuntimeMetricsIntegration()(Bun)bunRuntimeMetricsIntegration()
Recommendation logic:
| Feature | Recommend when... |
|---|---|
| Error Monitoring | Always — non-negotiable baseline |
| OTLP Integration | OTel tracing detected — replaces native Tracing |
| Tracing | Always for server apps — HTTP spans + DB spans are high-value; skip if OTel tracing detected |
| Logging | App uses winston, pino, bunyan, or needs log-to-trace correlation |
| Profiling | Node.js only — performance-critical service; native addon compatible; skip if OTel tracing detected (requires |
| AI Monitoring | App calls OpenAI, Anthropic, LangChain, Vercel AI, or Google GenAI |
| Crons | App uses node-cron, Bull, BullMQ, Agenda, or any scheduled task pattern |
| Metrics | App needs custom counters, gauges, or histograms |
| Runtime Metrics | Any Node.js or Bun service wanting automatic memory/CPU/event-loop visibility |
OTel tracing detected: "I see OpenTelemetry tracing in the project. I recommend Sentry's OTLP integration for tracing (via your existing OTel setup) + Error Monitoring + Sentry Logging [+ Metrics/Crons/AI Monitoring if applicable]. Shall I proceed?"
No OTel: "I recommend setting up Error Monitoring + Tracing. Want me to also add Logging or Profiling?"
根据检测结果给出具体的配置建议,不要提出开放式问题,直接给出方案:
检测到OTel的处理路径:
- 检测到OTel链路追踪(中存在
package.json或@opentelemetry/sdk-node,或源码中存在@opentelemetry/sdk-trace-node)→ 使用OTLP路径:通过NodeTracerProvider启用@sentry/node-core/light;不要设置otlpIntegration();Sentry会自动将错误与OTel链路关联tracesSampleRate
推荐的核心覆盖功能:
- ✅ 错误监控 —— 必选;捕获未处理异常、Promise拒绝以及框架错误
- ✅ 链路追踪 —— 通过OpenTelemetry自动监控HTTP、数据库和队列操作
可选的增强可观测性功能:
- ⚡ 日志记录 —— 通过实现结构化日志;当检测到
Sentry.logger.*/winston/pino或需要日志与链路关联时推荐使用bunyan - ⚡ 性能分析 —— 持续CPU分析(仅支持Node.js;Bun和Deno暂不支持);OTLP路径下不可用
- ⚡ AI监控 —— 支持OpenAI、Anthropic、LangChain、Vercel AI SDK;检测到AI/LLM调用时推荐使用
- ⚡ 任务调度监控 —— 检测遗漏或失败的定时任务;检测到node-cron、Bull或Agenda时推荐使用
- ⚡ 指标监控 —— 自定义计数器、仪表盘、分布统计;需要自定义关键指标时推荐使用
- ⚡ 运行时指标 —— 自动收集内存、CPU和事件循环指标;(Node.js)/
nodeRuntimeMetricsIntegration()(Bun)bunRuntimeMetricsIntegration()
推荐逻辑:
| 功能 | 推荐场景 |
|---|---|
| 错误监控 | 始终启用 —— 不可缺少的基础功能 |
| OTLP集成 | 检测到OTel链路追踪 —— 替代原生链路追踪 |
| 链路追踪 | 服务器应用必选 —— HTTP链路和数据库链路价值高;检测到OTel链路追踪时跳过 |
| 日志记录 | 应用使用winston、pino、bunyan,或需要日志与链路关联 |
| 性能分析 | 仅Node.js —— 性能敏感型服务;兼容原生插件;检测到OTel链路追踪时跳过(需要 |
| AI监控 | 应用调用OpenAI、Anthropic、LangChain、Vercel AI或Google GenAI |
| 任务调度监控 | 应用使用node-cron、Bull、BullMQ、Agenda或任何定时任务模式 |
| 指标监控 | 应用需要自定义计数器、仪表盘或直方图 |
| 运行时指标 | 任何需要自动监控内存/CPU/事件循环的Node.js或Bun服务 |
检测到OTel链路追踪时的话术: “我在项目中检测到了OpenTelemetry链路追踪。我推荐使用Sentry的OTLP集成实现链路追踪(基于你已有的OTel配置)+ 错误监控 + Sentry日志记录 [+ 若适用则添加指标监控/任务调度监控/AI监控]。是否继续?”
未检测到OTel时的话术: “我推荐配置错误监控 + 链路追踪。需要我同时添加日志记录或性能分析吗?”
Phase 3: Guide
阶段3:引导
Runtime: Node.js
运行时:Node.js
Option 1: Wizard (Recommended for Node.js)
选项1:向导工具(Node.js推荐方式)
You need to run this yourself — the wizard opens a browser for login and requires interactive input that the agent can't handle. Copy-paste into your terminal:npx @sentry/wizard@latest -i nodeIt handles login, org/project selection, SDK installation,creation, and package.json script updates.instrument.jsOnce it finishes, come back and skip to Verification.
If the user skips the wizard, proceed with Option 2 (Manual Setup) below.
你需要自行运行此命令 —— 向导会打开浏览器进行登录,需要交互式操作,无法由代理完成。请复制以下命令到终端执行:npx @sentry/wizard@latest -i node它会处理登录、组织/项目选择、SDK安装、创建以及package.json脚本更新。instrument.js完成后返回,直接跳转到验证步骤。
如果用户跳过向导工具,请继续执行选项2(手动配置)。
Option 2: Manual Setup — Node.js
选项2:手动配置 — Node.js
Install
安装
bash
npm install @sentry/node --savebash
npm install @sentry/node --saveor
或
yarn add @sentry/node
yarn add @sentry/node
or
或
pnpm add @sentry/node
undefinedpnpm add @sentry/node
undefinedCreate the Instrument File
创建Instrument文件
CommonJS ():
instrument.jsjavascript
// instrument.js — must be loaded before all other modules
const Sentry = require("@sentry/node");
Sentry.init({
dsn: process.env.SENTRY_DSN ?? "___DSN___",
sendDefaultPii: true,
// 100% in dev, lower in production
tracesSampleRate: process.env.NODE_ENV === "development" ? 1.0 : 0.1,
// Capture local variable values in stack frames
includeLocalVariables: true,
enableLogs: true,
});ESM ():
instrument.mjsjavascript
// instrument.mjs — loaded via --import flag before any other module
import * as Sentry from "@sentry/node";
Sentry.init({
dsn: process.env.SENTRY_DSN ?? "___DSN___",
sendDefaultPii: true,
tracesSampleRate: process.env.NODE_ENV === "development" ? 1.0 : 0.1,
includeLocalVariables: true,
enableLogs: true,
});CommonJS格式():
instrument.jsjavascript
// instrument.js —— 必须在所有其他模块之前加载
const Sentry = require("@sentry/node");
Sentry.init({
dsn: process.env.SENTRY_DSN ?? "___DSN___",
sendDefaultPii: true,
// 开发环境采样100%,生产环境降低采样率
tracesSampleRate: process.env.NODE_ENV === "development" ? 1.0 : 0.1,
// 在堆栈帧中捕获局部变量值
includeLocalVariables: true,
enableLogs: true,
});ESM格式():
instrument.mjsjavascript
// instrument.mjs —— 通过--import参数在所有其他模块之前加载
import * as Sentry from "@sentry/node";
Sentry.init({
dsn: process.env.SENTRY_DSN ?? "___DSN___",
sendDefaultPii: true,
tracesSampleRate: process.env.NODE_ENV === "development" ? 1.0 : 0.1,
includeLocalVariables: true,
enableLogs: true,
});Start Your App with Sentry Loaded First
确保Sentry优先加载并启动应用
CommonJS — add as the very first line of your entry file:
require("./instrument")javascript
// app.js
require("./instrument"); // must be first
const express = require("express");
// ... rest of your appESM — use the flag so Sentry loads before all other modules (Node.js 18.19.0+ required):
--importbash
node --import ./instrument.mjs app.mjsAdd to scripts:
package.jsonjson
{
"scripts": {
"start": "node --import ./instrument.mjs server.mjs",
"dev": "node --import ./instrument.mjs --watch server.mjs"
}
}Or via environment variable (useful for wrapping existing start commands):
bash
NODE_OPTIONS="--import ./instrument.mjs" npm startCommonJS格式 —— 在入口文件的第一行添加:
require("./instrument")javascript
// app.js
require("./instrument"); // 必须是第一行
const express = require("express");
// ... 应用其余代码ESM格式 —— 使用参数确保Sentry在所有模块之前加载(需要Node.js 18.19.0+):
--importbash
node --import ./instrument.mjs app.mjs将命令添加到的脚本中:
package.jsonjson
{
"scripts": {
"start": "node --import ./instrument.mjs server.mjs",
"dev": "node --import ./instrument.mjs --watch server.mjs"
}
}或通过环境变量设置(适合包装已有的启动命令):
bash
NODE_OPTIONS="--import ./instrument.mjs" npm startFramework Error Handlers
框架错误处理器
Register the Sentry error handler after all routes so it can capture framework errors:
Express:
javascript
const express = require("express");
const Sentry = require("@sentry/node");
const app = express();
// ... your routes
// Add AFTER all routes — captures 5xx errors by default
Sentry.setupExpressErrorHandler(app);
// Optional: capture 4xx errors too
// Sentry.setupExpressErrorHandler(app, {
// shouldHandleError(error) { return error.status >= 400; },
// });
app.listen(3000);Fastify:
javascript
const Fastify = require("fastify");
const Sentry = require("@sentry/node");
const fastify = Fastify();
// Add BEFORE routes (unlike Express!)
Sentry.setupFastifyErrorHandler(fastify);
// ... your routes
await fastify.listen({ port: 3000 });Koa:
javascript
const Koa = require("koa");
const Sentry = require("@sentry/node");
const app = new Koa();
// Add as FIRST middleware (catches errors thrown by later middleware)
Sentry.setupKoaErrorHandler(app);
// ... your other middleware and routes
app.listen(3000);Hapi (async — must await):
javascript
const Hapi = require("@hapi/hapi");
const Sentry = require("@sentry/node");
const server = Hapi.server({ port: 3000 });
// ... your routes
// Must await — Hapi registration is async
await Sentry.setupHapiErrorHandler(server);
await server.start();Connect:
javascript
const connect = require("connect");
const Sentry = require("@sentry/node");
const app = connect();
// Add BEFORE routes (like Fastify and Koa)
Sentry.setupConnectErrorHandler(app);
// ... your middleware and routes
require("http").createServer(app).listen(3000);NestJS — has its own dedicated skill with full coverage:
Use theskill instead. NestJS uses a separate package (sentry-nestjs-sdk) with NestJS-native constructs:@sentry/nestjs,SentryModule.forRoot(),SentryGlobalFilter,@SentryTraceddecorators, and GraphQL/Microservices support. Load that skill for complete NestJS setup.@SentryCron
Vanilla Node.js module — wrap request handler manually:
httpjavascript
const http = require("http");
const Sentry = require("@sentry/node");
const server = http.createServer((req, res) => {
Sentry.withIsolationScope(() => {
try {
// your handler
res.end("OK");
} catch (err) {
Sentry.captureException(err);
res.writeHead(500);
res.end("Internal Server Error");
}
});
});
server.listen(3000);Framework error handler summary:
| Framework | Function | Placement | Async? |
|---|---|---|---|
| Express | | After all routes | No |
| Fastify | | Before routes | No |
| Koa | | First middleware | No |
| Hapi | | Before | Yes |
| Connect | | Before routes | No |
| NestJS | → Use | Dedicated skill | — |
在所有路由之后注册Sentry错误处理器,以便捕获框架错误:
Express:
javascript
const express = require("express");
const Sentry = require("@sentry/node");
const app = express();
// ... 你的路由
// 在所有路由之后添加 —— 默认捕获5xx错误
Sentry.setupExpressErrorHandler(app);
// 可选:同时捕获4xx错误
// Sentry.setupExpressErrorHandler(app, {
// shouldHandleError(error) { return error.status >= 400; },
// });
app.listen(3000);Fastify:
javascript
const Fastify = require("fastify");
const Sentry = require("@sentry/node");
const fastify = Fastify();
// 在路由之前添加(与Express不同!)
Sentry.setupFastifyErrorHandler(fastify);
// ... 你的路由
await fastify.listen({ port: 3000 });Koa:
javascript
const Koa = require("koa");
const Sentry = require("@sentry/node");
const app = new Koa();
// 作为第一个中间件添加(捕获后续中间件抛出的错误)
Sentry.setupKoaErrorHandler(app);
// ... 你的其他中间件和路由
app.listen(3000);Hapi(异步操作 — 必须使用await):
javascript
const Hapi = require("@hapi/hapi");
const Sentry = require("@sentry/node");
const server = Hapi.server({ port: 3000 });
// ... 你的路由
// 必须使用await — Hapi的注册是异步操作
await Sentry.setupHapiErrorHandler(server);
await server.start();Connect:
javascript
const connect = require("connect");
const Sentry = require("@sentry/node");
const app = connect();
// 在路由之前添加(与Fastify和Koa相同)
Sentry.setupConnectErrorHandler(app);
// ... 你的中间件和路由
require("http").createServer(app).listen(3000);NestJS —— 有专门的技能提供完整覆盖:
请改用技能。 NestJS使用单独的包(sentry-nestjs-sdk),支持NestJS原生结构:@sentry/nestjs、SentryModule.forRoot()、SentryGlobalFilter、@SentryTraced装饰器, 以及GraphQL/微服务支持。加载该技能以完成完整的NestJS配置。@SentryCron
原生Node.js 模块 —— 手动包装请求处理器:
httpjavascript
const http = require("http");
const Sentry = require("@sentry/node");
const server = http.createServer((req, res) => {
Sentry.withIsolationScope(() => {
try {
// 你的处理器逻辑
res.end("OK");
} catch (err) {
Sentry.captureException(err);
res.writeHead(500);
res.end("Internal Server Error");
}
});
});
server.listen(3000);框架错误处理器汇总:
| 框架 | 函数 | 位置 | 是否异步 |
|---|---|---|---|
| Express | | 所有路由之后 | 否 |
| Fastify | | 路由之前 | 否 |
| Koa | | 第一个中间件 | 否 |
| Hapi | | | 是 |
| Connect | | 路由之前 | 否 |
| NestJS | → 使用 | 专用技能 | — |
Runtime: Bun
运行时:Bun
No wizard available for Bun. Manual setup only.
Bun暂无向导工具。 仅支持手动配置。
Install
安装
bash
bun add @sentry/bunbash
bun add @sentry/bunCreate instrument.ts
(or instrument.js
)
instrument.tsinstrument.js创建instrument.ts
(或instrument.js
)
instrument.tsinstrument.jstypescript
// instrument.ts
import * as Sentry from "@sentry/bun";
Sentry.init({
dsn: process.env.SENTRY_DSN ?? "___DSN___",
sendDefaultPii: true,
tracesSampleRate: process.env.NODE_ENV === "development" ? 1.0 : 0.1,
enableLogs: true,
});typescript
// instrument.ts
import * as Sentry from "@sentry/bun";
Sentry.init({
dsn: process.env.SENTRY_DSN ?? "___DSN___",
sendDefaultPii: true,
tracesSampleRate: process.env.NODE_ENV === "development" ? 1.0 : 0.1,
enableLogs: true,
});Start Your App with --preload
--preload使用--preload
启动应用
--preloadbash
bun --preload ./instrument.ts server.tsAdd to :
package.jsonjson
{
"scripts": {
"start": "bun --preload ./instrument.ts server.ts",
"dev": "bun --watch --preload ./instrument.ts server.ts"
}
}bash
bun --preload ./instrument.ts server.ts添加到:
package.jsonjson
{
"scripts": {
"start": "bun --preload ./instrument.ts server.ts",
"dev": "bun --watch --preload ./instrument.ts server.ts"
}
}Bun.serve() — Auto-Instrumentation
Bun.serve() — 自动插桩
@sentry/bunBun.serve()--preloadBun.serve()typescript
// server.ts
const server = Bun.serve({
port: 3000,
fetch(req) {
return new Response("Hello from Bun!");
},
});@sentry/bunBun.serve()--preloadBun.serve()typescript
// server.ts
const server = Bun.serve({
port: 3000,
fetch(req) {
return new Response("Hello from Bun!");
},
});Framework Error Handlers on Bun
Bun上的框架错误处理器
Bun can run Express, Fastify, Hono, and Elysia. Use the same import and the error handler functions (re-exported by ):
@sentry/bun@sentry/node@sentry/buntypescript
import * as Sentry from "@sentry/bun";
import express from "express";
const app = express();
// ... routes
Sentry.setupExpressErrorHandler(app);
app.listen(3000);Bun可以运行Express、Fastify、Hono和Elysia。使用相同的导入,并使用的错误处理器函数(由重新导出):
@sentry/bun@sentry/node@sentry/buntypescript
import * as Sentry from "@sentry/bun";
import express from "express";
const app = express();
// ... 路由
Sentry.setupExpressErrorHandler(app);
app.listen(3000);Bun Feature Support
Bun功能支持情况
| Feature | Bun Support | Notes |
|---|---|---|
| Error Monitoring | ✅ Full | Same API as Node |
| Tracing | ✅ Via | Most auto-instrumentations work |
| Logging | ✅ Full | |
| Profiling | ❌ Not available | |
| Metrics | ✅ Full | |
| Runtime Metrics | ✅ Full | |
| Crons | ✅ Full | |
| AI Monitoring | ✅ Full | OpenAI, Anthropic integrations work |
| 功能 | Bun支持情况 | 说明 |
|---|---|---|
| 错误监控 | ✅ 完整支持 | 与Node.js API相同 |
| 链路追踪 | ✅ 通过 | 大多数自动插桩功能可用 |
| 日志记录 | ✅ 完整支持 | |
| 性能分析 | ❌ 暂不支持 | |
| 指标监控 | ✅ 完整支持 | |
| 运行时指标 | ✅ 完整支持 | |
| 任务调度监控 | ✅ 完整支持 | |
| AI监控 | ✅ 完整支持 | OpenAI、Anthropic集成可用 |
Runtime: Deno
运行时:Deno
No wizard available for Deno. Manual setup only. Requires Deno 2.0+. Deno 1.x is not supported. Usespecifier. Thenpm:registry is deprecated.deno.land/x/sentry
Deno暂无向导工具。 仅支持手动配置。 需要Deno 2.0+。 Deno 1.x版本不被支持。 使用标识符。npm:注册表已被弃用。deno.land/x/sentry
Install via deno.json
(Recommended)
deno.json通过deno.json
安装(推荐方式)
deno.jsonjson
{
"imports": {
"@sentry/deno": "npm:@sentry/deno@10.42.0"
}
}Or import directly with the specifier:
npm:typescript
import * as Sentry from "npm:@sentry/deno";json
{
"imports": {
"@sentry/deno": "npm:@sentry/deno@10.42.0"
}
}或直接使用标识符导入:
npm:typescript
import * as Sentry from "npm:@sentry/deno";Initialize — Add to Entry File
初始化 — 添加到入口文件
typescript
// main.ts — Sentry.init() must be called before any other code
import * as Sentry from "@sentry/deno";
Sentry.init({
dsn: Deno.env.get("SENTRY_DSN") ?? "___DSN___",
sendDefaultPii: true,
tracesSampleRate: Deno.env.get("DENO_ENV") === "development" ? 1.0 : 0.1,
enableLogs: true,
});
// Your application code follows
Deno.serve({ port: 8000 }, (req) => {
return new Response("Hello from Deno!");
});Unlike Node.js and Bun, Deno does not have aor--preloadflag. Sentry must be the first--importin your entry file.import
typescript
// main.ts —— Sentry.init()必须在其他代码之前调用
import * as Sentry from "@sentry/deno";
Sentry.init({
dsn: Deno.env.get("SENTRY_DSN") ?? "___DSN___",
sendDefaultPii: true,
tracesSampleRate: Deno.env.get("DENO_ENV") === "development" ? 1.0 : 0.1,
enableLogs: true,
});
// 你的应用代码写在后面
Deno.serve({ port: 8000 }, (req) => {
return new Response("Hello from Deno!");
});与Node.js和Bun不同,Deno没有或--preload参数。Sentry必须是入口文件中的第一个--import。import
Required Deno Permissions
Deno所需权限
The SDK requires network access to reach your Sentry ingest domain:
bash
deno run \
--allow-net=o<ORG_ID>.ingest.sentry.io \
--allow-read=./src \
--allow-env=SENTRY_DSN,SENTRY_RELEASE \
main.tsFor development, works but is not recommended for production.
--allow-allSDK需要网络权限以连接到你的Sentry数据接收域名:
bash
deno run \\
--allow-net=o<ORG_ID>.ingest.sentry.io \\
--allow-read=./src \\
--allow-env=SENTRY_DSN,SENTRY_RELEASE \\
main.ts开发环境下可以使用,但不推荐在生产环境使用。
--allow-allDeno Cron Integration
Deno任务调度集成
Deno provides native cron scheduling. Use for automatic monitoring:
denoCronIntegrationtypescript
import * as Sentry from "@sentry/deno";
import { denoCronIntegration } from "@sentry/deno";
Sentry.init({
dsn: Deno.env.get("SENTRY_DSN") ?? "___DSN___",
integrations: [denoCronIntegration()],
});
// Cron is automatically monitored
Deno.cron("daily-cleanup", "0 0 * * *", () => {
// cleanup logic
});Deno提供原生任务调度功能。使用实现自动监控:
denoCronIntegrationtypescript
import * as Sentry from "@sentry/deno";
import { denoCronIntegration } from "@sentry/deno";
Sentry.init({
dsn: Deno.env.get("SENTRY_DSN") ?? "___DSN___",
integrations: [denoCronIntegration()],
});
// 任务调度会被自动监控
Deno.cron("daily-cleanup", "0 0 * * *", () => {
// 清理逻辑
});Deno Feature Support
Deno功能支持情况
| Feature | Deno Support | Notes |
|---|---|---|
| Error Monitoring | ✅ Full | Unhandled exceptions + |
| Tracing | ✅ Custom OTel | Automatic spans for |
| Logging | ✅ Full | |
| Profiling | ❌ Not available | No profiling addon for Deno |
| Metrics | ✅ Full | |
| Runtime Metrics | ❌ Not available | No runtime metrics integration for Deno |
| Crons | ✅ Full | |
| AI Monitoring | ✅ Partial | Vercel AI SDK integration works; OpenAI/Anthropic via |
| 功能 | Deno支持情况 | 说明 |
|---|---|---|
| 错误监控 | ✅ 完整支持 | 未处理异常 + |
| 链路追踪 | ✅ 自定义OTEL | 自动为 |
| 日志记录 | ✅ 完整支持 | |
| 性能分析 | ❌ 暂不支持 | 暂无针对Deno的性能分析插件 |
| 指标监控 | ✅ 完整支持 | |
| 运行时指标 | ❌ 暂不支持 | 暂无针对Deno的运行时指标集成 |
| 任务调度监控 | ✅ 完整支持 | |
| AI监控 | ✅ 部分支持 | Vercel AI SDK集成可用;OpenAI/Anthropic需通过 |
OTLP Integration (OTel-First Projects — Node.js Only)
OTLP集成(仅适用于以OTel为主的Node.js项目)
Use this path only when OpenTelemetry tracing was detected in Phase 1 (e.g.,or@opentelemetry/sdk-nodein@opentelemetry/sdk-trace-node). For projects without an existing OTel setup, use the standardpackage.jsonpath above.@sentry/node
The OTLP integration uses — a lightweight Sentry SDK that does not bundle its own OpenTelemetry. Instead, it hooks into the user's existing OTel and exports spans to Sentry via OTLP.
@sentry/node-core/lightTracerProvider仅当阶段1中检测到OpenTelemetry链路追踪时使用此路径 (例如中存在package.json或@opentelemetry/sdk-node)。 对于没有现有OTel配置的项目,请使用上文的标准@opentelemetry/sdk-trace-node路径。@sentry/node
OTLP集成使用 —— 轻量级Sentry SDK,不包含内置的OpenTelemetry。相反,它会挂钩到用户已有的OTel ,并通过OTLP将链路导出到Sentry。
@sentry/node-core/lightTracerProviderWhen to Use
使用场景
| Scenario | Recommended path |
|---|---|
| New project, no existing OTel | Standard |
| Existing OTel setup, want Sentry tracing | |
| Existing OTel setup, sending to own Collector | |
| 场景 | 推荐路径 |
|---|---|
| 新项目,无现有OTel | 标准 |
| 已有OTel配置,需要Sentry链路追踪 | |
| 已有OTel配置,发送到自有Collector | |
Install
安装
bash
npm install @sentry/node-core @opentelemetry/api @opentelemetry/sdk-trace-node @opentelemetry/sdk-trace-basebash
npm install @sentry/node-core @opentelemetry/api @opentelemetry/sdk-trace-node @opentelemetry/sdk-trace-baseor
或
yarn add @sentry/node-core @opentelemetry/api @opentelemetry/sdk-trace-node @opentelemetry/sdk-trace-base
yarn add @sentry/node-core @opentelemetry/api @opentelemetry/sdk-trace-node @opentelemetry/sdk-trace-base
or
或
pnpm add @sentry/node-core @opentelemetry/api @opentelemetry/sdk-trace-node @opentelemetry/sdk-trace-base
> The `@opentelemetry/*` packages are peer dependencies. If the project already has them installed, skip duplicates.pnpm add @sentry/node-core @opentelemetry/api @opentelemetry/sdk-trace-node @opentelemetry/sdk-trace-base
> `@opentelemetry/*`包是对等依赖项。如果项目已安装这些包,请跳过重复安装。Initialize
初始化
javascript
// instrument.mjs — load via --import flag before any other module
import { NodeTracerProvider } from '@opentelemetry/sdk-trace-node';
import * as Sentry from '@sentry/node-core/light';
import { otlpIntegration } from '@sentry/node-core/light/otlp';
// Register the user's OTel TracerProvider first
const provider = new NodeTracerProvider();
provider.register();
Sentry.init({
dsn: process.env.SENTRY_DSN ?? '___DSN___',
sendDefaultPii: true,
enableLogs: true,
// Do NOT set tracesSampleRate — OTel controls sampling
integrations: [
otlpIntegration({
// Export OTel spans to Sentry via OTLP (default: true)
setupOtlpTracesExporter: true,
}),
],
});With a custom Collector endpoint:
javascript
Sentry.init({
dsn: process.env.SENTRY_DSN ?? '___DSN___',
integrations: [
otlpIntegration({
collectorUrl: 'http://localhost:4318/v1/traces',
}),
],
});javascript
// instrument.mjs —— 通过--import参数在所有其他模块之前加载
import { NodeTracerProvider } from '@opentelemetry/sdk-trace-node';
import * as Sentry from '@sentry/node-core/light';
import { otlpIntegration } from '@sentry/node-core/light/otlp';
// 先注册用户的OTel TracerProvider
const provider = new NodeTracerProvider();
provider.register();
Sentry.init({
dsn: process.env.SENTRY_DSN ?? '___DSN___',
sendDefaultPii: true,
enableLogs: true,
// 不要设置tracesSampleRate —— OTel控制采样
integrations: [
otlpIntegration({
// 通过OTLP将OTel链路导出到Sentry(默认:true)
setupOtlpTracesExporter: true,
}),
],
});使用自定义Collector端点:
javascript
Sentry.init({
dsn: process.env.SENTRY_DSN ?? '___DSN___',
integrations: [
otlpIntegration({
collectorUrl: 'http://localhost:4318/v1/traces',
}),
],
});Start Your App
启动应用
Same pattern as the standard Node.js setup:
--importbash
node --import ./instrument.mjs app.mjs与标准Node.js配置相同,使用模式:
--importbash
node --import ./instrument.mjs app.mjsKey Differences from Standard @sentry/node
@sentry/node与标准@sentry/node
的主要区别
@sentry/node| Aspect | | |
|---|---|---|
| OTel bundled | ✅ Yes — built-in TracerProvider | ❌ No — uses your existing provider |
| Tracing control | | OTel SDK controls sampling |
| Auto-instrumentation | ✅ Built-in (HTTP, DB, etc.) | ❌ You manage OTel instrumentations |
| Profiling | ✅ Available | ❌ Not compatible |
| Error ↔ trace linking | ✅ Automatic | ✅ Automatic (via |
| Package size | Larger (includes OTel) | Smaller (light mode) |
| 方面 | | |
|---|---|---|
| 内置OTel | ✅ 是 —— 包含内置TracerProvider | ❌ 否 —— 使用用户已有的Provider |
| 链路追踪控制 | 在 | OTel SDK控制采样 |
| 自动插桩 | ✅ 内置(HTTP、数据库等) | ❌ 用户自行管理OTel插桩 |
| 性能分析 | ✅ 可用 | ❌ 不兼容 |
| 错误与链路关联 | ✅ 自动关联 | ✅ 自动关联(通过 |
| 包大小 | 较大(包含OTel) | 较小(轻量模式) |
For Each Agreed Feature
针对每个确认的功能
Load the corresponding reference file and follow its steps:
| Feature | Reference file | Load when... |
|---|---|---|
| Error Monitoring | | Always (baseline) — captures, scopes, enrichment, beforeSend |
| OTLP Integration | See OTLP Integration above | OTel tracing detected — replaces native Tracing |
| Tracing | | OTel auto-instrumentation, custom spans, distributed tracing, sampling; skip if OTel tracing detected |
| Logging | | Structured logs, |
| Profiling | | Node.js only — CPU profiling, Bun/Deno gaps documented; skip if OTel tracing detected |
| Metrics | | Custom counters, gauges, distributions |
| Runtime Metrics | See inline below | Automatic memory, CPU, and event loop metrics for Node.js and Bun |
| Crons | | Scheduled job monitoring, node-cron, Bull, Agenda, Deno.cron |
| AI Monitoring | Load | OpenAI, Anthropic, LangChain, Vercel AI, Google GenAI |
For each feature: read the reference file, follow its steps exactly, and verify before moving on.
加载对应的参考文件并按照步骤操作:
| 功能 | 参考文件 | 加载时机 |
|---|---|---|
| 错误监控 | | 始终加载(基础功能)—— 捕获、作用域、增强、beforeSend |
| OTLP集成 | 参见上文OTLP集成 | 检测到OTel链路追踪 —— 替代原生链路追踪 |
| 链路追踪 | | OTel自动插桩、自定义链路、分布式追踪、采样;检测到OTel链路追踪时跳过 |
| 日志记录 | | 结构化日志、 |
| 性能分析 | | 仅Node.js —— CPU分析,Bun/Deno不支持;检测到OTel链路追踪时跳过 |
| 指标监控 | | 自定义计数器、仪表盘、分布统计 |
| 运行时指标 | 参见下文内联内容 | 自动收集Node.js和Bun的内存、CPU和事件循环指标 |
| 任务调度监控 | | 定时任务监控、node-cron、Bull、Agenda、Deno.cron |
| AI监控 | 加载 | OpenAI、Anthropic、LangChain、Vercel AI、Google GenAI |
针对每个功能:读取参考文件,严格按照步骤操作,并在进行下一步前验证配置。
Runtime Metrics
运行时指标
Automatically collect Node.js and Bun runtime health metrics (memory, CPU utilization, event loop delay/utilization, uptime) at a configurable interval. Metrics appear in Sentry's Metrics product under the / namespace.
node.runtime.*bun.runtime.*Node.js — add to your :
nodeRuntimeMetricsIntegration()instrument.jsjavascript
const Sentry = require("@sentry/node");
Sentry.init({
dsn: process.env.SENTRY_DSN,
integrations: [
Sentry.nodeRuntimeMetricsIntegration(),
// Optional: change collection interval (default 30 000 ms)
// Sentry.nodeRuntimeMetricsIntegration({ collectionIntervalMs: 60_000 }),
],
});Metrics collected by default: , , , , , , , .
node.runtime.mem.rssnode.runtime.mem.heap_usednode.runtime.mem.heap_totalnode.runtime.cpu.utilizationnode.runtime.event_loop.delay.p50node.runtime.event_loop.delay.p99node.runtime.event_loop.utilizationnode.runtime.process.uptimeBun — add to your :
bunRuntimeMetricsIntegration()instrument.tstypescript
import * as Sentry from "@sentry/bun";
import { bunRuntimeMetricsIntegration } from "@sentry/bun";
Sentry.init({
dsn: process.env.SENTRY_DSN,
integrations: [
bunRuntimeMetricsIntegration(),
// Optional: change collection interval (default 30 000 ms)
// bunRuntimeMetricsIntegration({ collectionIntervalMs: 60_000 }),
],
});Metrics collected: same as Node.js except no event loop delay percentiles (unavailable in Bun). Prefixed with .
bun.runtime.*自动收集Node.js和Bun的运行时健康指标(内存、CPU使用率、事件循环延迟/使用率、运行时间),可配置收集间隔。指标会显示在Sentry的Metrics产品中,命名空间为 / 。
node.runtime.*bun.runtime.*Node.js —— 在中添加:
instrument.jsnodeRuntimeMetricsIntegration()javascript
const Sentry = require("@sentry/node");
Sentry.init({
dsn: process.env.SENTRY_DSN,
integrations: [
Sentry.nodeRuntimeMetricsIntegration(),
// 可选:修改收集间隔(默认30000毫秒)
// Sentry.nodeRuntimeMetricsIntegration({ collectionIntervalMs: 60_000 }),
],
});默认收集的指标:、、、、、、、。
node.runtime.mem.rssnode.runtime.mem.heap_usednode.runtime.mem.heap_totalnode.runtime.cpu.utilizationnode.runtime.event_loop.delay.p50node.runtime.event_loop.delay.p99node.runtime.event_loop.utilizationnode.runtime.process.uptimeBun —— 在中添加:
instrument.tsbunRuntimeMetricsIntegration()typescript
import * as Sentry from "@sentry/bun";
import { bunRuntimeMetricsIntegration } from "@sentry/bun";
Sentry.init({
dsn: process.env.SENTRY_DSN,
integrations: [
bunRuntimeMetricsIntegration(),
// 可选:修改收集间隔(默认30000毫秒)
// bunRuntimeMetricsIntegration({ collectionIntervalMs: 60_000 }),
],
});收集的指标:与Node.js相同,但不包含事件循环延迟百分位数(Bun暂不支持)。指标前缀为。
bun.runtime.*Verification
验证
After setup, verify Sentry is receiving events:
javascript
// Add temporarily to your entry file or a test route, then remove
import * as Sentry from "@sentry/node"; // or @sentry/bun / @sentry/deno
Sentry.captureException(new Error("Sentry test error — delete me"));Or trigger an unhandled exception:
javascript
// In a route handler or startup — will be captured automatically
throw new Error("Sentry test error — delete me");Then check your Sentry Issues dashboard — the error should appear within ~30 seconds.
Verification checklist:
| Check | How |
|---|---|
| Error captured | Throw in a handler, verify in Sentry Issues |
| Tracing working | Check Performance tab — should show HTTP spans |
| Stack frame in Sentry should show variable values |
| Source maps working | Stack trace shows readable file names, not minified |
配置完成后,验证Sentry是否正在接收事件:
javascript
// 临时添加到入口文件或测试路由,之后删除
import * as Sentry from "@sentry/node"; // 或@sentry/bun / @sentry/deno
Sentry.captureException(new Error("Sentry测试错误 —— 请删除此代码"));或触发一个未处理异常:
javascript
// 在路由处理器或启动代码中添加 —— 会被自动捕获
throw new Error("Sentry测试错误 —— 请删除此代码");然后查看你的Sentry问题仪表板 —— 错误应该会在约30秒内显示。
验证清单:
| 检查项 | 检查方式 |
|---|---|
| 错误已捕获 | 在处理器中抛出错误,在Sentry问题列表中验证 |
| 链路追踪正常工作 | 查看Performance标签页 —— 应显示HTTP链路 |
| Sentry中的堆栈帧应显示变量值 |
| Source Maps正常工作 | 堆栈跟踪显示可读的文件名,而非混淆后的名称 |
Config Reference
配置参考
Sentry.init()
Core Options
Sentry.init()Sentry.init()
核心选项
Sentry.init()| Option | Type | Default | Notes |
|---|---|---|---|
| | — | Required. Also from |
| | — | 0–1; required to enable tracing; do not set when using OTLP path |
| | | Include IP, request headers, user info |
| | | Add local variable values to stack frames (Node.js) |
| | | Enable Sentry Logs product (v9.41.0+) |
| | | Also from |
| | — | Also from |
| | | Log SDK activity to console |
| | | Set |
| | | Fraction of error events to send (0–1) |
| | | Milliseconds to flush events before process exit |
| 选项 | 类型 | 默认值 | 说明 |
|---|---|---|---|
| | — | 必填项。也可通过 |
| | — | 0–1;启用链路追踪时必填;使用OTLP路径时不要设置 |
| | | 包含IP、请求头、用户信息 |
| | | 在堆栈帧中添加局部变量值(仅Node.js) |
| | | 启用Sentry Logs产品(v9.41.0+) |
| | | 也可通过 |
| | — | 也可通过 |
| | | 将SDK活动日志输出到控制台 |
| | | 测试环境中设置为 |
| | | 要发送的错误事件比例(0–1) |
| | | 进程退出前刷新事件的毫秒数 |
nativeNodeFetchIntegration()
Options
nativeNodeFetchIntegration()nativeNodeFetchIntegration()
选项
nativeNodeFetchIntegration()Configures outgoing / span capture. Since , response headers like are no longer captured automatically — use to opt in:
fetchundici@opentelemetry/instrumentation-undici@0.22.0content-lengthheadersToSpanAttributesjavascript
Sentry.init({
integrations: [
Sentry.nativeNodeFetchIntegration({
headersToSpanAttributes: {
requestHeaders: ["x-request-id"],
responseHeaders: ["content-length", "content-type"],
},
}),
],
});| Option | Type | Default | Notes |
|---|---|---|---|
| | | Record breadcrumbs for outgoing fetch requests |
| | — | Request header names to capture as span attributes |
| | — | Response header names to capture as span attributes |
配置 outgoing /链路捕获。自起,等响应头不再被自动捕获 —— 使用选择启用:
fetchundici@opentelemetry/instrumentation-undici@0.22.0content-lengthheadersToSpanAttributesjavascript
Sentry.init({
integrations: [
Sentry.nativeNodeFetchIntegration({
headersToSpanAttributes: {
requestHeaders: ["x-request-id"],
responseHeaders: ["content-length", "content-type"],
},
}),
],
});| 选项 | 类型 | 默认值 | 说明 |
|---|---|---|---|
| | | 为 outgoing fetch请求记录面包屑 |
| | — | 要捕获为链路属性的请求头名称 |
| | — | 要捕获为链路属性的响应头名称 |
otlpIntegration()
Options (@sentry/node-core/light/otlp
)
otlpIntegration()@sentry/node-core/light/otlpotlpIntegration()
选项(@sentry/node-core/light/otlp
)
otlpIntegration()@sentry/node-core/light/otlpFor OTel-first projects using . Import: .
@sentry/node-core/lightimport { otlpIntegration } from '@sentry/node-core/light/otlp'| Option | Type | Default | Purpose |
|---|---|---|---|
| | | Auto-configure OTLP exporter to send spans to Sentry; set |
| | | OTLP HTTP endpoint of an OTel Collector (e.g., |
适用于使用的以OTel为主的项目。导入方式:。
@sentry/node-core/lightimport { otlpIntegration } from '@sentry/node-core/light/otlp'| 选项 | 类型 | 默认值 | 用途 |
|---|---|---|---|
| | | 自动配置OTLP导出器以将链路发送到Sentry;如果已导出到自有Collector,请设置为 |
| | | OTel Collector的OTLP HTTP端点(例如 |
Graceful Shutdown
优雅关闭
Flush buffered events before process exit — important for short-lived scripts and serverless:
javascript
process.on("SIGTERM", async () => {
await Sentry.close(2000); // flush with 2s timeout
process.exit(0);
});进程退出前刷新缓冲的事件 —— 对短生命周期脚本和无服务器环境非常重要:
javascript
process.on("SIGTERM", async () => {
await Sentry.close(2000); // 2秒超时时间内刷新事件
process.exit(0);
});Environment Variables
环境变量
| Variable | Purpose | Runtime |
|---|---|---|
| DSN (alternative to hardcoding in | All |
| Deployment environment | All |
| Release version string (auto-detected from git) | All |
| Source map upload token | Build time |
| Org slug for source map upload | Build time |
| Project slug for source map upload | Build time |
| Set | Node.js |
| 变量 | 用途 | 运行时 |
|---|---|---|
| DSN(替代在 | 所有 |
| 部署环境 | 所有 |
| 版本字符串(从git自动检测) | 所有 |
| Source Map上传令牌 | 构建时 |
| Source Map上传的组织标识 | 构建时 |
| Source Map上传的项目标识 | 构建时 |
| 为ESM设置 | Node.js |
Source Maps (Node.js)
Source Maps(Node.js)
Readable stack traces in production require source map upload. Use or the webpack/esbuild/rollup plugins:
@sentry/clibash
npm install @sentry/cli --save-devbash
undefined生产环境中可读的堆栈跟踪需要上传Source Map。使用或webpack/esbuild/rollup插件:
@sentry/clibash
npm install @sentry/cli --save-devbash
undefinedCreate a Sentry auth token at sentry.io/settings/auth-tokens/
在sentry.io/settings/auth-tokens/创建Sentry授权令牌
Set in .env.sentry-build-plugin (gitignore this file):
在.env.sentry-build-plugin中设置(将此文件加入gitignore):
SENTRY_AUTH_TOKEN=sntrys_eyJ...
Add upload step to your build:
```json
{
"scripts": {
"build": "tsc && sentry-cli sourcemaps inject ./dist && sentry-cli sourcemaps upload ./dist"
}
}SENTRY_AUTH_TOKEN=sntrys_eyJ...
在构建步骤中添加上传命令:
```json
{
"scripts": {
"build": "tsc && sentry-cli sourcemaps inject ./dist && sentry-cli sourcemaps upload ./dist"
}
}Phase 4: Cross-Link
阶段4:跨服务关联
After completing backend setup, check for companion services:
bash
undefined后端配置完成后,检查是否存在配套服务:
bash
undefinedFrontend companion
配套前端
ls frontend/ web/ client/ ui/ 2>/dev/null
cat package.json 2>/dev/null | grep -E '"react"|"vue"|"svelte"|"next"'
ls frontend/ web/ client/ ui/ 2>/dev/null
cat package.json 2>/dev/null | grep -E '"react"|"vue"|"svelte"|"next"'
Other backend services
其他后端服务
ls ../go.mod ../requirements.txt ../Gemfile 2>/dev/null
If a frontend, framework-specific SDK, or other backend is found, suggest the matching skill:
**Dedicated JavaScript framework skills (prefer these over generic node-sdk):**
| Detected | Prefer skill | Why |
|----------|-------------|-----|
| NestJS (`@nestjs/core` in `package.json`) | [`sentry-nestjs-sdk`](../sentry-nestjs-sdk/SKILL.md) | Uses `@sentry/nestjs` with NestJS-native decorators, filters, and GraphQL support |
| Next.js (`next` in `package.json`) | [`sentry-nextjs-sdk`](../sentry-nextjs-sdk/SKILL.md) | Three-runtime architecture (browser, server, edge), `withSentryConfig`, source map upload |
**Frontend companions:**
| Detected | Suggest |
|---------|---------|
| React app (`react` in `package.json`) | [`sentry-react-sdk`](../sentry-react-sdk/SKILL.md) |
| Svelte/SvelteKit | [`sentry-svelte-sdk`](../sentry-svelte-sdk/SKILL.md) |
**Other backend companions:**
| Detected | Suggest |
|---------|---------|
| Go backend (`go.mod`) | [`sentry-go-sdk`](../sentry-go-sdk/SKILL.md) |
| Python backend (`requirements.txt`, `pyproject.toml`) | [`sentry-python-sdk`](../sentry-python-sdk/SKILL.md) |
| Ruby backend (`Gemfile`) | [`sentry-ruby-sdk`](../sentry-ruby-sdk/SKILL.md) |
Connecting frontend and backend with the same DSN or linked projects enables **distributed tracing** — stack traces that span your browser, API server, and database in a single trace view.
---ls ../go.mod ../requirements.txt ../Gemfile 2>/dev/null
如果检测到前端、框架专用SDK或其他后端服务,建议使用匹配的技能:
**JavaScript框架专用技能(优先于通用node-sdk):**
| 检测到的内容 | 优先使用的技能 | 原因 |
|----------|-------------|-----|
| NestJS(`package.json`中存在`@nestjs/core`) | [`sentry-nestjs-sdk`](../sentry-nestjs-sdk/SKILL.md) | 使用`@sentry/nestjs`,支持NestJS原生装饰器、过滤器和GraphQL支持 |
| Next.js(`package.json`中存在`next`) | [`sentry-nextjs-sdk`](../sentry-nextjs-sdk/SKILL.md) | 适配三运行时架构(浏览器、服务器、边缘端),支持`withSentryConfig`和Source Map上传 |
**配套前端:**
| 检测到的内容 | 建议使用的技能 |
|---------|---------|
| React应用(`package.json`中存在`react`) | [`sentry-react-sdk`](../sentry-react-sdk/SKILL.md) |
| Svelte/SvelteKit | [`sentry-svelte-sdk`](../sentry-svelte-sdk/SKILL.md) |
**其他配套后端:**
| 检测到的内容 | 建议使用的技能 |
|---------|---------|
| Go后端(`go.mod`) | [`sentry-go-sdk`](../sentry-go-sdk/SKILL.md) |
| Python后端(`requirements.txt`、`pyproject.toml`) | [`sentry-python-sdk`](../sentry-python-sdk/SKILL.md) |
| Ruby后端(`Gemfile`) | [`sentry-ruby-sdk`](../sentry-ruby-sdk/SKILL.md) |
使用相同的DSN或关联项目将前端和后端连接起来,可实现**分布式链路追踪** —— 在单个链路视图中跨浏览器、API服务器和数据库展示完整的堆栈跟踪。
---Troubleshooting
故障排除
| Issue | Cause | Solution |
|---|---|---|
| Events not appearing | | Ensure it's the first |
| Tracing spans missing | | Add |
| ESM instrumentation not working | Missing | Run with |
| Native addon incompatible | Profiling is not supported on Bun — remove |
| Deno: events not sent | Missing | Run with |
Deno: | Deprecated and frozen at v8.55.0 | Switch to |
| Integration not activated or minified code | Ensure |
| NestJS: errors not captured | Wrong SDK or missing filter | Use |
Hapi: | Not awaited | Must |
| Shutdown: events lost | Process exits before flush | Add |
| Stack traces show minified code | Source maps not uploaded | Configure |
| No traces appearing (OTLP) | Missing | Verify |
| OTLP: errors not linked to traces | | Ensure |
| Profiling not starting (OTLP) | Profiling requires | Profiling is not compatible with the OTLP path; use the standard |
| 问题 | 原因 | 解决方案 |
|---|---|---|
| 事件未显示 | | 确保它是第一个 |
| 链路追踪缺失 | 未设置 | 在 |
| ESM插桩不生效 | 缺少 | 使用 |
Bun上安装 | 原生插件不兼容 | Bun不支持性能分析 —— 移除 |
| Deno:事件未发送 | 缺少 | 使用 |
Deno: | 已被弃用并冻结在v8.55.0版本 | 切换到 |
| 集成未激活或代码已混淆 | 确保 |
| NestJS:错误未被捕获 | 使用了错误的SDK或缺少过滤器 | 使用 |
Hapi: | 未使用await | 必须在 |
| 关闭时:事件丢失 | 进程在刷新前退出 | 在SIGTERM/SIGINT处理器中添加 |
| 堆栈跟踪显示混淆后的代码 | 未上传Source Maps | 在构建步骤中配置 |
| OTLP模式下无链路显示 | 缺少 | 验证 |
| OTLP:错误未与链路关联 | 未注册 | 确保 |
| OTLP模式下性能分析未启动 | 性能分析需要 | 性能分析与OTLP路径不兼容;改用标准 |
| ", |