sentry简介
Sentry
是一个开源的错误追踪工具,可以帮助开发人员实时监控和修复系统中的错误。其专注于错误监控以及提取一切事后处理所需的信息;支持几乎所有主流开发语言(JS/Java/Python/php
)和平台, 并提供了web来展示输出错误。
sentry官网:sentry.io/
文档地址:docs.sentry.io/platforms/
sentry安装
- 官方推荐:
Docker
&Python
- 官方平台: sentry.io/
在Vue项目中使用sentry
- 新建一个vue项目
- 在项目中安装
@sentry/browser
@sentry/integrations
并在main.js中配置。官方文档
$ npm install @sentry/browser
$ npm install @sentry/integrations
// main.js
import Vue from 'vue'
import * as Sentry from '@sentry/browser';
import * as Integrations from '@sentry/integrations';
process.env.NODE_ENV === "production" && Sentry.init({
dsn: 'https://e028cb7b8dd645978cf5d84a@sentry.io/18726',
integrations: [new Integrations.Vue({Vue, attachProps: true})],
});
(注意区分环境,一般我们只关注生产环境中的error。)
现在当我们的代码,出现错误时,sentry会自动捕获到我们的错误,发邮件给你,然后就到了你填坑的时候了。
上传sourcemap
-
原因:通过上述步骤我们基本可以定位到错误的位置,但是在生产环境中,代码被混淆压缩,对于暴露Bug是没有意义的,所以我们要build项目时顺便向sentry的服务器上传项目的sourcemap文件,以便能快速准确定位错误所在。
-
在项目中新建.sentryclirc文件
[defaults] url = 'https://sentry.io/' org = 'bignox' project = 'test' [auth] token = cvbfdhb343h54h54546b5hn76
token字段可以在项目setting中看到。注意创建token时在默认权限基础上,在勾选
project write
权限
-
在项目中使用
@sentry/webpack-plugin
插件,sentry官方给出的自动化方案,可在build时自动上传sourcemap文件。const SentryWebpackPlugin = require('@sentry/webpack-plugin'); module.exports = { ... configureWebpack: config => { //生产and测试环境 let pluginsPro = [ new SentryWebpackPlugin({ include: './dist', ignoreFile: '.sentrycliignore', ignore: ['node_modules', 'webpack.config.js'], configFile: 'sentry.properties', release: 'ssp' + process.env.VERSION //仅仅是sourcemap的名字 }) ]; //开发环境 let pluginsDev = []; if(process.env.ENV === 'production') { config.plugins = [...config.plugins, ...pluginsPro]; } else { // 为开发环境修改配置... config.plugins = [...config.plugins, ...pluginsDev]; } } };
注意release字段要与main.js中的release字段相同,这样才能对应上。
// main.js import Vue from 'vue' import * as Sentry from '@sentry/browser'; import * as Integrations from '@sentry/integrations'; process.env.NODE_ENV === "production" && Sentry.init({ dsn: 'https://e02b7b8d45978c8f5d84a@sentry.io/1806', integrations: [new Integrations.Vue({Vue, attachProps: true})], release: 'ssp' + process.env.VERSION });
-
配置完,开始build试一下吧。
build完成后,后台就可以看到releases记录
点进去,就能看到上传的map文件
- 部署到线上后,当有error被捕获到,我们就可以直接定位到源代码处了🐂🍺
错误捕获
-
捕获错误或意外
在JS中,你可以通过把一个error对象传递给_captureException()_来将它当做一个事件对象被捕获。
try { aFunctionThatMightFail(); } catch (err) { Sentry.captureException(err); }
-
自动捕获