前端工程接入sentry 📣

5,119 阅读2分钟

我接入后的感受是:接入sentry不仅监控线上错误,快速溯源。还有一点,就是可以通过报错,了解到错误处理机制,了解到前端代码的一些隐形bug,规范代码

sentry 简介

  • 中文哨兵的意思,一个错误监控和收集的开源工具
  • 通过在要监控的项目中注入sdk,上报错误给服务端。
  • 服务端是数据管理平台,可企业自己搭建,也可直接使用官网平台。

接入步骤

  • 在平台创建项目
  • 注入sdk
// main.js(ts)
import '@/common/sentry'

// sentry.js
import * as Sentry from '@sentry/browser'
import { Integrations } from '@sentry/tracing'

const environment = DEPLOY_ENVIRONMENT || 'production'

Sentry.init({
 dsn: 'https://xxx@sentry.xxx.com/xxx', //sentry平台创建项目的唯一dsn,可在平台创建后找到
 integrations: [new Integrations.BrowserTracing()],
 tracesSampleRate: 1.0,
 environment,
 release: RELEASE_VERSION, // 定位错误在哪个版本,与sourcemap上传版本保持一致,可以把sourcemap文件与版本对应上
})

  • 上传sourcemap:用的是sentry-webpack-plugin
// 只配置生产环境 webpack.prod.conf.js
const SentryPlugin = require('@sentry/webpack-plugin')
const gitSha = require('child_process')
 .execSync('git rev-parse HEAD')
 .toString()
 .trim() //这个是获取提交版本的记录
 
 webpackConfig.plugins.push(
 new SentryPlugin({
   include: './dist', // 打包目录
   ignore: ['node_modules', 'build', 'docs', 'jekins'],
   // configFile: '../.sentryclirc', // 配置文件 默认~/.sentryclirc,找根目录下.sentryclirc文件
   release: process.env.RELEASE_VERSION,
   deleteAfterCompile: true,
 }),
)

  • 自定义上报错误信息
Sentry.captureMessage('海报头像生成失败')
scope.setUser(user)
setTag
...
  • 添加用户崩溃反馈弹窗
Sentry.init({
dsn:'https://xxx@xxx.ingest.sentry.io/xxx',
  beforeSend(event, hint) {
  // Check if it is an exception, and if so, show the report dialog
    if (event.exception) {
      Sentry.showReportDialog({ eventId: event.event_id });
    }
    return event;
  }
});
  • 接入邮箱📮报警
  • 性能监控与统计
  • ...

sentry 原理

  • window.onerror劫持,监听unhandledrejection事件,监听vue ErrorHandler方法
  • 如何上报
    • sentry.init()时会创建hub,并在其上绑定一个客户端client和一个空白作用域scope。
    • client 创建事件分发给transport
    • transport 统一处理ajax上报请求
const client = new BrowserClient({
  dsn: 'https://<key>@sentry.io/<project>',
});
 
const hub = new Hub(client);
 hub.configureScope(function(scope) {
  scope.setTag("a", "b");
});
 
hub.addBreadcrumb({ message: "crumb 1" });
hub.captureMessage("test");
 
try {
  a = b;
} catch (e) {
  hub.captureException(e);
}
 
hub.withScope(function(scope) {
  hub.addBreadcrumb({ message: "crumb 2" });
  hub.captureMessage("test2");
});

image.png

@see ️⭐️ mp.weixin.qq.com/s?__biz=MzA…

参考: