sentry系统监控前端异常

简介

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

vue项目实践

配置

基于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.webpack

  • 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的配置以下git

// 这里使用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中一致github

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组件的哪一行代码报错。web

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

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

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

相关文章
相关标签/搜索