使用 Sentry

有关安装和配置 Sentry 以进行崩溃报告的指南。


Sentry 是一个崩溃报告平台,可让你实时了解生产部署,并提供重现和修复崩溃的信息。

¥Sentry is a crash reporting platform that provides you with real-time insight into production deployments with info to reproduce and fix crashes.

它会通知你用户在使用你的应用时遇到的异常或错误,并在网络仪表板上为你组织它们。自动报告的异常包括堆栈跟踪、设备信息、版本和其他相关上下文。你还可以提供特定于你的应用的其他上下文,例如当前路由和用户 ID。

¥It notifies you of exceptions or errors that your users run into while using your app and organizes them for you on a web dashboard. Reported exceptions include stacktraces, device info, version, and other relevant context automatically. You can also provide additional context that is specific to your application such as the current route and user id.

Platform compatibility

Android DeviceAndroid EmulatoriOS DeviceiOS SimulatorWeb

安装和配置 Sentry

¥Install and configure Sentry

sentry-expo 已合并到 @sentry/react-native 中,现已弃用。我们建议升级到 SDK 50 以使用 @sentry/react-native 以获得最佳体验。如果你已经在使用 sentry-expo了解如何迁移

¥sentry-expo has been merged into @sentry/react-native and is now deprecated. We recommend upgrading to SDK 50 to use @sentry/react-native for the best experience. If you're already using sentry-expo, learn how to migrate.

1

注册 Sentry 账户并创建项目

¥Sign up for a Sentry account and create a project

在继续安装 Sentry 之前,你需要确保已创建 Sentry 账户和项目:

¥Before proceeding with installing Sentry, you'll need to make sure you have created a Sentry account and project:

1.1

注册 Sentry(免费套餐每月最多支持 5,000 个事件),并在仪表板中创建一个项目。记下你的组织别名、项目名称和 DSN,因为稍后你将需要它们:

¥Sign up for Sentry (the free tier supports up to 5,000 events per month), and create a project in your Dashboard. Take note of your organization slug, project name, and DSN as you'll need them later:

  • 组织 slug 可在“组织设置”选项卡中找到

    ¥organization slug is available in your Organization settings tab

  • 项目名称可在项目的“设置”>“项目”选项卡中找到(在列表中找到它)

    ¥project name is available in your project's Settings > Projects tab (find it in the list)

  • DSN 可在项目的设置 > 项目 > 项目名称 > SDK 设置部分 > 客户端密钥 (DSN) 选项卡中使用。

    ¥DSN is available in your project's Settings > Projects > Project name > Under SDK Setup section > Client Keys (DSN) tab.

1.2

转到 开发者设置 > 身份验证令牌 页面并创建一个新的 组织身份验证令牌。该令牌自动确定源映射上传和发布创建的范围。保存。

¥Go to the Developer Settings > Auth Tokens page and create a new Organization Auth Token. The token is automatically scoped for Source Map Upload and Release Creation. Save it.

一旦你拥有了这些:组织 slug、项目名称、DSN 和身份验证令牌,你就可以继续了。

¥Once you have each of these: organization slug, project name, DSN, and auth token, you're all set to proceed.

2

安装@sentry/react-native

¥Install @sentry/react-native

在项目目录中运行以下命令来安装来自 Sentry 团队的官方 React Native 库:

¥Run the following command in your project directory to install the official React Native library from the Sentry team:

Terminal
npx expo install @sentry/react-native

3

应用配置

¥App configuration

配置 @sentry/react-native 可以通过配置插件完成。将插件添加到项目的 应用配置 文件中:

¥Configuring @sentry/react-native can be done through the config plugin. Add the plugin to your project's app config file:

app.json
{
"expo": {
  "plugins": [
    [
      "@sentry/react-native/expo",
      {
        "organization": "sentry org slug, or use the `SENTRY_ORG` environment variable",
        "project": "sentry project name, or use the `SENTRY_PROJECT` environment variable",
        // If you are using a self-hosted instance, update the value of the url property
        // to point towards your self-hosted instance. For example, https://self-hosted.example.com/.
        "url": "https://sentry.io/"
      }
    ]
  ]
}
}

接下来,在你想要创建版本并将源映射上传到 Sentry 的环境中,你需要将 SENTRY_AUTH_TOKEN 环境变量设置为 Sentry 身份验证令牌。如果你使用 EAS Build,则可以通过 创建名为 SENTRY_AUTH_TOKEN 的密钥 设置环境变量。

¥Next, in an environment where you want to create releases and upload sourcemaps to Sentry, you will need to set the SENTRY_AUTH_TOKEN environment variable to your Sentry auth token. If you are using EAS Build, you can set the environment variable by creating a secret named SENTRY_AUTH_TOKEN.

Sentry 身份验证令牌应安全存储。不要将其提交到公共存储库,并像对待任何其他敏感 API 密钥一样对待它。
Are you using this library in a bare React Native app?

如果你不使用 持续的原生生成 (CNG),那么你应该使用 @sentry/wizard

¥If you do not use Continuous Native Generation (CNG), then you should use the @sentry/wizard.

4

更新 Metro 配置

¥Update Metro configuration

Sentry 连接到 Metro 以将 "调试 ID" 注入到源映射中。此调试 ID 用于将源映射与版本关联起来。要启用此功能,你需要将以下内容添加到 Metro.config.js(如果你还没有该文件,请在项目的根目录中创建它):

¥Sentry hooks into Metro to inject a "debug ID" into your source maps. This debug ID is used to associate source maps with releases. To enable this, you need to add the following to your metro.config.js (if you don't have the file yet, create it in the root of your project):

metro.config.js
// This replaces `const { getDefaultConfig } = require('expo/metro-config');`
const { getSentryExpoConfig } = require('@sentry/react-native/metro');

// This replaces `const config = getDefaultConfig(__dirname);`
const config = getSentryExpoConfig(__dirname);

module.exports = config;

5

初始化哨兵

¥Initialize Sentry

如果你的应用使用 Expo 路由,那么你可以自动配置 Sentry 以捕获当前路由并将其与错误报告一起传递。要进行设置,请在 根布局路由 中配置 Sentry 并添加导航集成。

¥If your app uses Expo Router, then you can configure Sentry automatically to capture the current route and pass it along with your error reports. To set this up, configure Sentry in the Root Layout route and add the navigation integration.

app/_layout.tsx
import { Slot, useNavigationContainerRef } from 'expo-router';
import { useEffect } from 'react';
import * as Sentry from '@sentry/react-native';
import { isRunningInExpoGo } from 'expo';

// Construct a new integration instance. This is needed to communicate between the integration and React
const navigationIntegration = Sentry.reactNavigationIntegration({
enableTimeToInitialDisplay: !isRunningInExpoGo(),
});

Sentry.init({
dsn: 'YOUR DSN HERE',
debug: true, // If `true`, Sentry will try to print out useful debugging information if something goes wrong with sending the event. Set it to `false` in production
tracesSampleRate: 1.0, // Set tracesSampleRate to 1.0 to capture 100% of transactions for tracing. Adjusting this value in production.
integrations: [
  // Pass integration
  navigationIntegration,
],
enableNativeFramesTracking: !isRunningInExpoGo(), // Tracks slow and frozen frames in the application
});

function RootLayout() {
// Capture the NavigationContainer ref and register it with the integration.
const ref = useNavigationContainerRef();

useEffect(() => {
  if (ref?.current) {
    navigationIntegration.registerNavigationContainer(ref);
  }
}, [ref]);

return <Slot />;
}

// Wrap the Root Layout route component with `Sentry.wrap` to capture gesture info and profiling data.
export default Sentry.wrap(RootLayout);

将以下内容添加到应用的主文件(例如 App.js)中:

¥Add the following to your app's main file such as App.js:

import * as Sentry from '@sentry/react-native';

Sentry.init({
dsn: 'YOUR DSN HERE',
debug: true, // If `true`, Sentry will try to print out useful debugging information if something goes wrong with sending the event. Set it to `false` in production
});

现在用 Sentry 封装应用的根组件。这可能是 App.js 或 index.js,具体取决于你的项目。

¥Now wrap the root component of your app with Sentry. This may be App.js or index.js depending on your project.

import * as Sentry from '@sentry/react-native';

// Your App component here

export default Sentry.wrap(App);

6

验证配置

¥Verify the configuration

创建应用的新版本并验证它是否正确上传源映射。你可能想在应用中添加一个按钮来测试它是否正常工作以及源映射是否按预期连接,例如:

¥Create a new release build of your app and verify that it uploads source maps correctly. You may want to add a button in your app to test that it is working and sourcemaps are wired up as expected, for example:

import { Button } from 'react-native';

// Inside some component
<Button title="Press me" onPress={() => { throw new Error('Hello, again, Sentry!'); }}/>

与 EAS 构建一起使用

¥Usage with EAS Build

确保在你的构建环境中设置了 SENTRY_AUTH_TOKEN,Sentry 会自动为你上传源映射。如果你在应用配置中使用环境变量而不是属性,请确保也设置了这些变量。

¥Ensure that SENTRY_AUTH_TOKEN is set in your build environment, and Sentry will automatically upload source maps for you. If you use environment variables rather than properties in your app config, ensure that those are set as well.

使用上述说明,在使用 EAS Build 时无需进行任何额外工作即可将 Sentry 集成到你的项目中。

¥Using the above instructions, no additional work is needed to integrate Sentry into your project when using EAS Build.

与 EAS 更新一起使用

¥Usage with EAS Update

运行 eas update 后,将源映射上传到 Sentry:

¥After running eas update, upload the source maps to Sentry:

Terminal
# Pass in the "dist" directory generated by `eas update` to the upload script
npx sentry-expo-upload-sourcemaps dist

就是这样!现在,你的更新错误将在 Sentry 中正确地用符号表示。

¥That's it! Errors for your updates will now be properly symbolicated in Sentry.

Do you want to publish an update and the sourcemaps in one command?

你可以将命令与 && 链接在一起,一步发布更新并上传源映射:

¥You can chain the commands together with && to publish an update and upload the sourcemaps in one step:

Terminal
eas update --branch <branch> && npx sentry-expo-upload-sourcemaps dist

了解有关 Sentry 的更多信息

¥Learn more about Sentry

Sentry 的作用不仅仅是捕获致命错误,还可以从其 JavaScript 使用 文档中了解有关如何使用 Sentry 的更多信息。

¥Sentry does more than just catch fatal errors, learn more about how to use Sentry from their JavaScript usage documentation.