Skip to main content

Sentry 插件

¥Sentry plugin

该插件使你能够使用 Sentry 跟踪 Strapi 应用中的错误。

¥This plugin enables you to track errors in your Strapi application using Sentry.

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

¥By using the Sentry plugin you can:

  • 在 Strapi 应用启动时初始化 Sentry 实例

    ¥Initialize a Sentry instance upon startup of a Strapi application

  • 将 Strapi 应用错误作为事件发送到 Sentry

    ¥Send Strapi application errors as events to Sentry

  • 在 Sentry 事件中包含其他元数据以协助调试

    ¥Include additional metadata in Sentry events to assist in debugging

  • 暴露 全局 Sentry 服务

    ¥Expose a global Sentry service

首先对 Sentry 插件进行 installing,然后对插件进行 configuring,以使你的 Strapi 应用能够将事件发送到 Sentry 实例。

¥Begin by first installing the Sentry plugin, and then configuring the plugin to enable your Strapi application to send events to the Sentry instance.

安装

¥Installation

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

¥Install the Sentry plugin by adding the dependency to your Strapi application as follows:

yarn add @strapi/plugin-sentry

配置

¥Configuration

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

¥Create or edit your ./config/plugins.js file to configure the Sentry plugin. The following properties are available:

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

示例配置:

¥An example configuration:

./config/plugins.js

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

环境配置

¥Environment configuration

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

¥Using the env utility, you can enable or disable the Sentry plugin based on the environment. For example, to only enable the plugin in your production environment:

config/plugins.js

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

全局 Sentry 服务接入

¥Global Sentry service access

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

¥After installing and configuring the plugin, you can access a Sentry service in your Strapi application as follows:



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


该服务公开了以下方法:

¥This service exposes the following methods:

方法描述参数
sendError()手动将错误发送到 Sentry。
getInstance()用于直接访问 Sentry 实例。

以下是每种方法的示例。

¥Below are examples for each method.

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;
}