sentry系统监控前端异常

2,337 阅读2分钟

简介

  前端异常监控系统,市面上有好多。为什么我们选择sentry呢?因为其较多的支持目前主流语言及框架的项目,比较成熟和稳定。而且开源,并且github上还有docker集成好的sentry安装环境。目前,多数公司在做前端异常监控时,都选择了开源的sentry。

vue项目实践

配置

基于vue的前端项目,我们按照一下步骤:

  • 1.首先在搭建的sentry系统上新建一个vue的项目。
  • 2.之后我们需要引入vue框架的sentry SDK。
      @sentry/browser:通过包含和配置Sentry,SDK将自动附加全局处理程序以捕获未捕获的异常和未处理的拒绝。
      @sentry/integrations:将捕获引发错误的Vue活动组件的名称和props状态。这是通过Vue的config.errorHandler钩子报告的。

npm install @sentry/browser.
npm install @sentry/integrations.

  • 3.在vue项目的main.js中导入插件及相关配置
import * as Sentry from '@sentry/browser'
import * as Integrations from '@sentry/integrations'
// sentry config
  Sentry.init({
    dsn: 'https://<key>@sentry.io/<project>', // 项目的dns
    integrations: [ new Integrations.Vue({ Vue, attachProps: true }) ] // 
  })

sourcemap

  上面的配置已经能使我们的异常上报到sentry系统,但异常报错的位置是被webpack压缩过的js文件,我们很难识别到底是项目中的哪一个组件哪一行代码。为了使上报异常能快速定位到代码位置,我们引入sourcemap的解析。
  我们需要引入一个组件@sentry/webpack-plugin,在vue项目的vue.config.js的配置如下

// 这里使用commonJS模式引入组件
const SentryPlugin = require('@sentry/webpack-plugin')
module.exports = { 
	configureWebpack: config => {
	    config.plugins.push(
	      new SentryPlugin({
	        project: 'project-name', // 项目名称
	        apiKey: token, // sentry的API TOKEN
	        suppressErrors: true, // 上传失败时不阻碍webpack继续执行
	        release: 'version', // sentry项目上的release版本
	        include: '.', // 需要上传的文件包含哪些
	        filenameTransform: filename => {
	          return `~/${filename}` // 上传文件的对应web页面引入资源的目录接口
	        }
	      })
	    )
	  },
	productionSourceMap: true
}

main.js要添加release的配置与vue.config.js中一致

  Sentry.init({
    dsn: 'https://<key>@sentry.io/<project>', // 项目的dns
    integrations: [ new Integrations.Vue({ Vue, attachProps: true }) ],
    release: 'version' // sentry项目上的release版本
  })
}

  以上配置完成后,我们就可以在sentry系统上看到报错匹配到source.map.js,具体到vue组件的哪一行代码报错。

  注意:这里引入webpack-plugin,开启了项目的sourcemap。webpack构建时,压缩的js chunk文件会生成对应的map.js文件,为了防止项目源码泄漏,我们生产环境,构建完成后手动删除map.js文件。

find . -name "*.js.map" | xargs rm -rf

  还有一种不通过插件的方式,上传项目的map.js文件。项目build完成后,遍历js下的文件,调用sentry提供的上传接口,将文件上传到对应的release下。新建项目release也是通过调用sentry提供的api完成。这里就不详细说明了。