还不懂前端监控,一文教你使用

980 阅读5分钟

一、为什么选择Sentry

现在市场上有不少的成熟方案,包括fundebug、webfunny、阿里ARMS、腾讯BadJS、Sentry。

  1. 4. 成熟方案比较

监控平台

是否支持异常监控

是否支持性能监控

是否有免费版

是否开源

是否能私有化部署

是否支持多端多语言

是否有告警系统

备注

mmTrix

×

×

×

×

×

云服务

监控宝

×

×

×

×

×

云服务

OneAPM

×

×

×

-

×

服务端和客户端分离,支持语言有限

听云

×

×

×

×

FrontJs

-

×

-

×

价格阶梯服务,免费版功能受限,没有性能监控

FunDebug

×

-

-

免费版功能受限

Webfunny

×

-

×

免费版功能受限

阿里ARMS

-

×

×

×

15天免费

腾讯BadJS

×

×

×

web-monitoring

×

由个人开发者开源

newrelic

Sentry

从这个表中分析可知,一个兼顾异常监控和性能监控,且能够私有化部署的平台有Sentry、newrelic、web-monitoring。 如果小团队仅使用前端监控的话,web-monitoring就可以满足需要了。 在考虑产品问世时间,市场占有率之后我选择了Sentry。

二、Sentry快速上手

1、创建监控项目

2、选择你自己前端项目框架,我(react)

3、点击创建项目

4、按照提示在前端项目中安装 sentry

我的安装:

pnpm install --save @sentry/react

在项目最外层初始化 sentry 配置

Sentry.init({
    // 这个填你项目中的
  dsn: "https://609a39a92cc4a5cb14974697f5e1e489@o4505633004912640.ingest.sentry.io/4505662834212864",
  integrations: [
    new Sentry.BrowserTracing({
      // Set 'tracePropagationTargets' to control for which URLs distributed tracing should be enabled
      tracePropagationTargets: ["localhost", "https:yourserver.io/api/"],
    }),
    new Sentry.Replay(),
  ],
  // Performance Monitoring
  tracesSampleRate: 1.0, // Capture 100% of the transactions, reduce in production!
  // Session Replay
  replaysSessionSampleRate: 0.1, // This sets the sample rate at 10%. You may want to change it to 100% while in development and then sample at a lower rate in production.
  replaysOnErrorSampleRate: 1.0, // If you're not already sampling the entire session, change the sample rate to 100% when sampling sessions where errors occur.
});

const container = document.getElementById(“app”);
const root = createRoot(container);
root.render(<App />)

然后保存,刷新浏览器,在请求中可以看到 sentry 对应的请求了,此时代表项目安装sentry好了

前端发生异常时,sentry会采集内容

  • 异常信息:抛出异常的 error 信息,Sentry 会自动捕捉。

  • 用户信息:用户的信息(登录名、id、level 等),所属机构信息,所属公司信息。

  • 行为信息:用户的操作过程,例如登陆后进入 xx 页面,点击 xx 按钮,Sentry 会自动捕捉。

  • 版本信息:运行项目的版本信息(测试、生产、灰度),以及版本号。

  • 设备信息:项目使用的平台,web 项目包括运行设备信息及浏览器版本信息。小程序项目包括运行手机的手机型号、系统版本及微信版本。

  • 时间戳:记录异常发生时间,Sentry 会自动捕捉。

  • 异常等级:Sentry将异常划分等级 "fatal", "error", "warning", "log", "info", "debug", "critical"

  • 平台信息:记录异常发生的项目。

最终会调用Fetch请求上报到对应的Sentry服务器上

此时拥有的功能**:报错提示,性能监控**

三、Sentry手动上报

1、Sentry 不会自动捕获捕获的异常:如果编写了 try/catch 而不重新抛出异常,则该异常将永远不会出现在 Sentry

import * as Sentry from "@sentry/vue";

// 异常捕获
try {
  aFunctionThatMightFail();
} catch (err) {
  Sentry.captureException(err);
}
// 消息捕获
Sentry.captureMessage("Something went wrong");
// 设置级别
// 级别枚举 ["fatal", "error", "warning", "log", "info", "debug", "critical"]
Sentry.captureMessage("this is a debug message", "debug");
// 设置自定义内容
Sentry.captureMessage("Something went fundamentally wrong", {
  contexts: {
    text: {
      hahah: 22,
    },
  },
  level: Sentry.Severity.Info,
});
// 异常设置级别
Sentry.withScope(function(scope) {
  scope.setLevel("info");
  Sentry.captureException(new Error("custom error"));
});
// 在scope外,继承前面的外置级别
Sentry.captureException(new Error("custom error 2"));

// 设置其他参数 tags, extra, contexts, user, level, fingerprint
// https://docs.sentry.io/platforms/javascript/guides/vue/enriching-events/context/
// Object / Function
Sentry.captureException(new Error("something went wrong"), {
  tags: {
    section: "articles",
  },
});
Sentry.captureException(new Error("clean as never"), scope => {
    scope.clear();
    // 设置用户信息: 
    scope.setUser({ “email”: “xx@xx.cn”})
    // 给事件定义标签: 
    scope.setTags({ ‘api’, ‘api/ list / get’})
    // 设置事件的严重性:
    scope.setLevel(‘error’)
    // 设置事件的分组规则: 
    scope.setFingerprint(['{{ default }}', url])
    // 设置附加数据: 
    scope.setExtra(‘data’, { request: { a: 1, b: 2 })

  return scope;
});

// 事件分组
Sentry.configureScope(scope => scope.setTransactionName("UserListView"));

// 事件自定义 
// 全局
Sentry.configureScope(function(scope) {
  scope.addEventProcessor(function(event, hint) {
    // TODO
    // returning null 会删除这个事件
    return event;
  });
});

// 局部事件
Sentry.withScope(function(scope) {
  scope.addEventProcessor(function(event, hint) {
    // TODO
    // returning null 会删除这个事件
    return event;
  });
  Sentry.captureMessage("Test");
});

2、有一些问题需要主动上报,比如axios请求报错

Sentry.captureException(error)

3、崩溃处理,如果程序意外关闭,可以在close事件处理

Sentry.close(2000).then(function() {
  // perform something after close
});

四、Sentry 源码错误定位

sentry通过上传sourcemap,可以把错误在源码中定位到

具体配置方式:

前端项目中执行下面命令

npx @sentry/wizard@latest -i sourcemaps

选择你自己的打包工具,我使用的是vite

在打包工具vite配置文件中,写入上述内容

import { sentryVitePlugin } from '@sentry/vite-plugin'

export default defineConfig(() => {
  return {
    plugins: [
      ...
      // Put the Sentry vite plugin after all other plugins
      sentryVitePlugin({
        authToken: process.env.SENTRY_AUTH_TOKEN,
        org: 'mk-ah',
        project: 'javascript-react'
      }),
      ...
    ],
    ...
    // build configure
    build: {
      ...
      sourcemap: true, // Source map generation must be turned on
      ...
    }
  }
})

我这里不需要 ci/cd

这样,就安装好了,出错时会指向具体的源码位置

五、Sentry webhook通知(结合飞书)

**目的:**当Sentry捕获到错误后,主动通知开发人员

1、创建飞书异常报警群

2、添加一个群机器人

3、创建一个飞书捷径指令

4、配置飞书捷径

选择sentry,并点击完成

添加http请求

请求方式:post URL:刚刚的步骤2机器人的url复制粘贴过来

数据类型:application/json

请求体:

{

  "msg_type": "post",
  "content": {
          "post": {
                  "zh_cn": {
                          "title": "Crush预警",
                          "content": [
                                  [
                                            {
                                                  "tag": "a",
                                                  "text": "测试通知",
                                                  "href": "https://mk-ah.sentry.io/issues/?referrer=sidebar"
                                          }
                                  ]
                          ]
                  }
          }
  }
}

点击完成,给指令改名,预警,保存即可

5、配置sentry

先开通webhook

设置-集成-webhook

配置4的图2的url

给指定项目添加通知规则

这里我们可以点击 send test notification测试一下

然后把这条通知保存即可

这样完整的通知就配置好了