优秀的编程知识分享平台

网站首页 > 技术文章 正文

使用 sentry 搭建前后端错误监控系统-之react+python 详细指南

nanyue 2025-03-10 18:56:37 技术文章 6 ℃

一、前言

任何应用都会因为各种意外或者疏忽,出现各种bug,虽然经历过大量测试,但是依然无法覆盖全部的情况,用户也不会按照我们的预期方式进行操作,所以在上线后的错误收集就变得非常重要。

二、sentry 简介

sentry-正如它的英文意思一样:哨兵,sentry就像一个哨兵一样,实时监控生产环境上的系统运行状态,一旦发生异常立刻会把报错的路由路径、错误所在文件等详细信息通知我们,并且利用错误信息的堆栈跟踪快速定位到需要处理的问题。

它还有如下这些优点:

  • 开源
  • 前后端都支持
  • 广泛的语言和框架支持,例如:

  • 支持 SourceMap,这在前端打包压缩混淆代码的时候很方便我们定位问题

Sentry 官方提供的免费服务有次数限制,达到一定限制后继续使用就需要收费了,但是我们可以利用 Sentry 的开源库在自己的服务器上搭建服务。

三、服务端搭建

官网推荐使用docker,所以本教程使用docker进行搭建。

环境要求:

  • Docker 19.03.6+
  • Compose 1.24.1+
  • 4 CPU Cores
  • 8 GB 内存
  • 20 GB 硬盘空间
git clone https://github.com/getsentry/onpremise.git
复制代码

进入克隆下来的文件夹,运行./install.sh脚本,在安装过程中,会提示您是否要创建用户帐户。如果您需要安装不被提示阻止,请运行./install.sh \--no-user-prompt

安装成功后,访问 localhost:9000 就能访问 sentry 管理系统了。

四、客户端React中使用

安装SDK:

npm install --save @sentry/react @sentry/tracing
复制代码

配置 sentry:

import React from "react";
import ReactDOM from "react-dom";
import * as Sentry from "@sentry/react";
import { Integrations } from "@sentry/tracing";
import App from "./App";

Sentry.init({
  dsn: "https://examplePublicKey@o0.ingest.sentry.io/0",
  integrations: [new Integrations.BrowserTracing()],

  // We recommend adjusting this value in production, or using tracesSampler
  // for finer control
  tracesSampleRate: 1.0,
});

ReactDOM.render(, document.getElementById("root"));
复制代码

常见的配置选项如下:

  • dsn 连接客户端(项目)与sentry服务端,让两者能够通信的钥匙
  • debug 打开或关闭调试模式
  • release 设置发布 , 识别新问题、回归、问题是否在下一个版本中得到解决
  • environment 设置环境
  • tunnel 设置将用于传输捕获事件的 URL,而不是使用 DSN
  • sampleRate 配置错误事件的采样率,范围为0.01.0
  • maxBreadcrumbs 应捕获的面包屑总量
  • attachStacktrace 启用后,堆栈跟踪会自动附加到所有记录的消息
  • denyUrls 不应发送给 Sentry 的错误 URL
  • allowUrls 匹配应专门发送给 Sentry 的错误 URL
  • autoSessionTracking 发送会话事件
  • initialScope 初始范围的数据
  • normalizeDepth 数据标准化到给定的深度,例如([Object][Array]),默认3层

sentry还提供了两个高阶组件:ErrorBoundary 和 withProfiler。

ErrorBoundary 组件自动捕获 JavaScript 错误并将其从 React 组件树内部发送到 Sentry,并呈现回退 UI。

import React from "react";
import * as Sentry from "@sentry/react";


  
;
复制代码

ErrorBoundary 有如下配置项:

  • showDialog 如果在错误边界捕获错误时应呈现 Sentry 用户反馈小部件
  • dialogOptions 反馈部件配置选项
  • fallback 当错误边界捕获错误时要呈现的 React 元素
  • onError当错误边界遇到错误时调用的函数
  • onMountonUnmount
  • beforeCapture 在将错误发送到 Sentry 之前调用的函数

withProfiler主要是对react组件进行性能分析,分为三个方面,react.mountreact.render,和react.update

Source Maps支持:

现在的前端代码都是用各种构建打包工具例如webpack进行了压缩混淆,必须使用source maps才能很好的进行问题定位,sentry也提供了webpack插件来支持。

npm install --save-dev @sentry/webpack-plugin
复制代码

然后在sentry的后台管理系统中,为我们的 API 生成访问令牌。

配置webpack:

const SentryWebpackPlugin = require("@sentry/webpack-plugin");

module.exports = {
  // other webpack configuration
  devtool: 'source-map',
  plugins: [
    new SentryWebpackPlugin({
      // sentry-cli configuration
      authToken: process.env.SENTRY_AUTH_TOKEN,
      org: "example-org",
      project: "example-project",
      release: process.env.SENTRY_RELEASE,

      // webpack-specific configuration
      include: ".",
      ignore: ["node_modules", "webpack.config.js"],
    }),
  ],
};
复制代码

五、客户端python中使用

安装SDK:

pip install --upgrade sentry-sdk
复制代码

配置 sentry:

import sentry_sdk

sentry_sdk.init(
    "https://examplePublicKey@o0.ingest.sentry.io/0",

    # Set traces_sample_rate to 1.0 to capture 100%
    # of transactions for performance monitoring.
    # We recommend adjusting this value in production.
    traces_sample_rate=1.0,
)
复制代码

配置项与react是一样的。

如果你使用的是老的版本raven,稍加改动即可迁移成功:

旧:

import raven
client = raven.Client('https://examplePublicKey@o0.ingest.sentry.io/0', release="1.3.0")
复制代码

新:

import sentry_sdk
sentry_sdk.init('https://examplePublicKey@o0.ingest.sentry.io/0', release='1.3.0')
复制代码

旧:

client.tags_context({'key': 'value'})
复制代码

新:

sentry_sdk.set_tag('key', 'value')
复制代码

六、主动捕获错误

sentry可以自动捕获程序中的大部分错误,但是还有一些异步错误,例如接口请求错误等,需要我们自己手动捕获:

axios.post(url)
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    Sentry.captureException(new Error("something went wrong"), scope);
  })
复制代码

七、用户识别

可以通过setUser来识别用户:

Sentry.setUser({ email: "john.doe@example.com" });
复制代码

有如下选项:

  • id 用户内部标识符。
  • username用户名
  • email 邮箱
  • ip_address用户的 IP 地址

八、设置标签

sentry 中的标签功能强大,例如过滤器和标签分布图。标签还可以帮助您快速访问相关事件并查看一组事件的标签分布。标签的常见用途包括主机名、平台版本和用户语言。

Sentry.setTag("page_locale", "de-at");
复制代码

九、附件

Sentry 可以丰富你的事件和进一步的调查研究,通过存储额外的文件,例如配置和日志文件作为附件。附件将会被保留30天,如果超出了总存储,附件将不会被保存。

import * as Sentry from "@sentry/react";
public attachmentUrlFromDsn(dsn: Dsn, eventId: string) {
  const { host, path, projectId, port, protocol, user } = dsn;
  return `${protocol}://${host}${port !== '' ? `:${port}` : ''}${
    path !== '' ? `/${path}` : ''
  }/api/${projectId}/events/${eventId}/attachments/?sentry_key=${user}&sentry_version=7&sentry_client=custom-javascript`;
}

Sentry.addGlobalEventProcessor((event: Event) => {
  try {
    const client = Sentry.getCurrentHub().getClient();
    const endpoint = attachmentUrlFromDsn(
      client.getDsn(),
      event.event_id
    );
    const formData = new FormData();
    formData.append(
      'my-attachment',
      new Blob([JSON.stringify({ logEntries: ["my log"] })], {
        type: 'application/json',
      }),
      'logs.json'
    );
    fetch(endpoint, {
      method: 'POST',
      body: formData,
    }).catch((ex) => {
      // we have to catch this otherwise it throws an infinite loop in Sentry
      console.error(ex);
    });
    return event;
  } catch (ex) {
    console.error(ex);
  }
});
最近发表
标签列表