将Sentry与Strapi相结合的详细指南

369 阅读2分钟

将Sentry与Strapi相结合

Sentry是一个通知用户在使用应用程序时遇到的异常或错误的平台。它也可以用于性能监控,设置错误警报和监控每个版本的健康状况。Sentry可以通过几种方式与Strapi集成。

使用官方插件:@strapi/plugin-sentry

  • 这是Strapi的官方Sentry插件,可以用来跟踪错误
  • 使用命令安装该插件
yarn add @strapi/plugin-sentry // yarn
npm install @strapi/plugin-sentry // npm
  • 为了跟踪错误事件,我们必须将该插件添加到插件的配置文件中,即启用它。./config/plugins.js
  sentry: {
    enabled: true,
    config: {
      dsn: process.env.SENTRY_DSN,
      sendMetadata: true,
    },
  }

下面是使用officail插件集成Sentry的拉动请求的链接。

Note: strapi-plugin-sentry was the plugin to be used with Strapi v3 and it is deprecated with Strapi v4

在Strapi中创建自定义中间件

  • 这种方法可以用来利用Sentry的优势,如性能监控、跟踪发布健康状况、报告错误。
  • 初始化Sentry SDK并在自定义中间件中捕获异常。
  • 可以传递给SDK的常见选项有:
    • dsn: Dsn是在Sentry中创建的项目的唯一标识符,它将让SDK知道在哪里记录事件。
    • environment:这将设置项目的当前环境,这也将有助于在Sentry中根据环境过滤错误或异常。
    • tracesSampleRate:这将介于0和1之间,0表示0%,1表示100%。这可以用来决定在Sentry中可以记录的交易的百分比。
// src/middlewares/sentry.js

Sentry.init({
  dsn: process.env.SENTRY_DSN,
  environment: strapi.config.environment,
  integrations: [new Sentry.Integrations.Http({ tracing: true })],
  tracesSampleRate: 1.0,
});

module.exports = (config, { strapi }) => {
  return async (ctx, next) => {
    try {
      await next();
    } catch (error) {
      // Error object or string can be passed to captureException
      Sentry.captureException(error);
      throw error;
    }
  };
};
  • 一旦创建了中间件,就需要将其添加到中间件的配置文件中:
// config/middleware.js

[
  // ... existing middlewares
  'global::sentry',
];

以下是通过创建自定义中间件来集成Sentry的拉动请求的链接。