Koa

Learn about using Sentry with Koa.

This guide explains how to set up Sentry in your Koa application.

如果你还没有 Sentry 账户和项目,请免费注册 Sentry,然后返回此页面。

除了捕获错误,你还可以通过启用跟踪来监控多个服务或应用程序之间的交互。你还可以使用性能分析收集和分析真实用户的性能数据。

选择你希望安装的 Sentry 功能(除错误监控外),以获取相应的安装和配置说明。

Sentry 通过在应用程序运行时中使用 SDK 来捕获数据。

Copied
npm install @sentry/node @sentry/profiling-node --save

Sentry 应尽可能早地在你的应用程序中初始化。确保你在应用程序中引入其他任何模块之前调用 Sentry.init,否则自动仪器化将无法为这些模块工作。

完成此操作后,Sentry 的 Node SDK 将捕获未处理的异常以及应用程序的跟踪数据。

要导入并初始化 Sentry,你需要创建一个名为 instrument.js 的文件:

instrument.js
Copied
const Sentry = require("@sentry/node");
const { nodeProfilingIntegration } = require("@sentry/profiling-node");

// Ensure to call this before requiring any other modules!
Sentry.init({
  dsn: "https://examplePublicKey@o0.ingest.sentry.io/0",
  integrations: [
    // Add our Profiling integration
    nodeProfilingIntegration(),
  ],

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

  // Set sampling rate for profiling
  // This is relative to tracesSampleRate
  profilesSampleRate: 1.0,
});

一旦你设置了 tracesSampleRate,性能仪器化将自动启用。阅读关于 自动仪器化 的内容,了解更多 SDK 可以为你自动仪器化的内容。

你也可以手动捕获性能数据 - 详情请参阅 自定义仪器化

为了确保 Sentry 可以自动仪器化应用程序中的所有模块,你需要在引入其他任何模块之前,先引入 instrument.js 文件:

Copied
// Require this first!
require("./instrument");

// Now require other modules
const Koa = require("koa");
const Sentry = require("@sentry/node");

const app = new Koa();

Sentry.setupKoaErrorHandler(app);

// Add your routes, etc.

app.listen(3030);

根据您项目的设置方式,Sentry 错误中的堆栈跟踪可能不会显示为您的实际代码。

要解决此问题,请将源映射上传到 Sentry。最简单的方法是使用 Sentry 向导:

Copied
npx @sentry/wizard@latest -i sourcemaps

向导将引导您完成以下步骤:

  • 登录 Sentry 并选择一个项目
  • 安装必要的 Sentry 包
  • 配置您的构建工具以生成和上传源映射
  • 配置您的 CI 以上传源映射

有关源映射的更多信息或更多上传选项,请参阅我们的 源映射文档

此代码片段包含一个故意的错误,以便你可以测试并确保一切设置正确后正常工作。

Copied
router.get("/debug-sentry", function () {
  throw new Error("My first Sentry error!");
});

了解更多关于手动捕获错误或消息的内容,请参阅我们的 使用文档

要查看和解决记录的错误,请登录 sentry.io 并选择你的项目。点击错误标题将打开一个页面,在该页面上你可以查看详细信息并将其标记为已解决。