哨兵 Sentry

跟踪 Strapi 应用程序中的错误。

此插件可让您使用 Sentry 跟踪 Strapi 应用程序中的错误。

通过使用 Sentry 插件,您可以:

  • 在 Strapi 应用程序启动时初始化 Sentry 实例
  • 将 Strapi 应用程序错误作为事件发送到 Sentry
  • 在 Sentry 事件中包含其他元数据以协助调试
  • 公开 全局 Sentry 服务

首先 安装 Sentry 插件,然后 配置 插件以使您的 Strapi 应用程序能够将事件发送到 Sentry 实例。

安装

通过将依赖项添加到您的 Strapi 应用程序来安装 Sentry 插件,如下所示:

bash
yarn
bash
yarn add @strapi/plugin-sentry

配置

创建或编辑您的 ./config/plugins.js 文件以配置 Sentry 插件。以下属性可用:

属性类型默认值说明
dsn字符串null您的 Sentry 数据源名称
sendMetadata布尔值true插件是否应将其他信息(例如操作系统、浏览器等)附加到发送到 Sentry 的事件。
initobject{}初始化期间直接传递给 Sentry 的配置对象。有关所有可用选项,请参阅官方 Sentry 文档

示例配置:

js
./config/plugins.js
js
module.exports = ({ env }) => ({
  // ...
  sentry: {
    enabled: true,
    config: {
      dsn: env('SENTRY_DSN'),
      sendMetadata: true,
    },
  },
  // ...
})

环境配置

使用 env 实用程序,您可以根据环境启用或禁用 Sentry 插件。例如,仅在您的 production 环境中启用该插件:

js
config/plugins.js
js
module.exports = ({ env }) => ({
  // ...
  sentry: {
    enabled: env('NODE_ENV') === 'production',
  },
  // ...
})

全局 Sentry 服务访问

安装并配置插件后,您可以在 Strapi 应用程序中访问 Sentry 服务,如下所示:

js
const sentryService = strapi.plugin('sentry').service('sentry')

此服务公开以下方法:

方法说明参数
sendError()手动向 Sentry 发送错误。
  • error:要发送的错误。
  • configureScope:可选。使您能够自定义错误事件。
有关更多详细信息,请参阅官方 Sentry 文档
getInstance()用于直接访问 Sentry 实例。

以下是每种方法的示例。

js
sendError
js
try {
  // Your code here
}
catch (error) {
  // Either send a simple error
  strapi
    .plugin('sentry')
    .service('sentry')
    .sendError(error)

  // Or send an error with a customized Sentry scope
  strapi
    .plugin('sentry')
    .service('sentry')
    .sendError(error, (scope, sentryInstance) => {
      // Customize the scope here
      scope.setTag('my_custom_tag', 'Tag value')
    })
  throw error
}