Sentry在vue中的使用
vue2中接入sentry
- vue项目中安装依赖
sentry运行需要以下两个依赖:
@sentry/vue
(Sentry's Vue SDK)@sentry/tracing
(instruments performance data)
安装命令:
npm install --save @sentry/vue @sentry/tracing
- vue项目中配置sentry
这里介绍vue2.x项目中配置sentry的方式,在main.js中需要引入sentry相关模块,以及配置Sentry配置项,接入代码如下:
import * as Sentry from "@sentry/vue";
import { Integrations } from "@sentry/tracing";
Sentry.init({
Vue,
dsn: "http://[email protected]:9000/7",
integrations: [
new Integrations.BrowserTracing({
routingInstrumentation: Sentry.vueRouterInstrumentation(router),
tracingOrigins: ["localhost", "my-site-url.com", /^\//],
}),
],
// Set tracesSampleRate to 1.0 to capture 100%
// of transactions for performance monitoring.
// We recommend adjusting this value in production
tracesSampleRate: 1.0,
});
- 验证
在项目中故意写错一行代码,在后台即可看到报错
上传sourcemaps
- 描述
将sentry引入vue中初步可以满足监控错误的需求但是并不能看到具体错误的代码所在行,需要上传sourcemaps文件才可定位到错误代码具体的位置。 - 上传sourcemaps
安装sourcemaps的webpack插件
npm install --save-dev @sentry/webpack-plugin
注意:若安装失败需要将npm镜像源设置为淘宝镜像
在项目中配置sourcemaps
(1)在根目录下新建.sentryclirc文件
文件内容如下:
[defaults]
url=https://sentry.io/ //网站地址
org=org //组织名称,在设置的组织设置中查看
project=project //创建的项目名称
[auth]
token=token //API token,在后台设置中生成,注意在生成API token的时候将project:write勾选上
例如:
[defaults]
url='https://sentry.io/'
org= 'it-95c'
project='mytest'
[auth]
token='be168779697b4da0a8e48c706c9e2a83093a47d497ca496ea03f17f7c9d0e54c'
(2)开启productionSourceMap
在vue.config.js中添加productionSourceMap:true
(3)在vue.config.js中配置sourcemaps
配置案例如下:
const SentryCliPlugin = require('@sentry/webpack-plugin')
configureWebpack: {
// provide the app's title in webpack's name field, so that
// it can be accessed in index.html to inject the correct title.
name: name,
resolve: {
alias: {
'@': resolve('src')
}
},
plugins:[
new SentryCliPlugin({
include: "./dist", // 作用的文件夹,如果只想js报错就./dist/js
release: '1.0', // 一致的版本号
configFile: "sentry.properties", // 不用改
ignore: ['node_modules', 'webpack.config.js'],
urlPrefix: "~/",//这里指的你项目需要观测的文件如果你的项目有publicPath这里加上就对了
cleanArtifacts: true,
// authToken: 'be168779697b4da0a8e48c706c9e2a83093a47d497ca496ea03f17f7c9d0e54c',
// org: "it-95c",
// project: "mytest",
})
]
}
注意:
①release版本号需要和Sentry.init()配置项中的tracesSampleRate版本号一致。
②注释处:authToken、org、project如果在.sentryclirc文件中配置可省略。
③urlPrefix尤其注意,填写的路径要和线上对应的url资源的相对路径一致,由此可知开发环境中无法使用sourcemaps。
(4)本地开发环境使用sourcemaps
因为sourcemaps是在线上环境中使用的,因此在本地开发环境中需要安装服务启动项目模拟线上环境方可使用。
①安装node.js静态文件服务器
npm install -g serve
②使用npm run build将项目打包
③启动服务器
serve -s dist
④启动项目后在sentry后台即可查看错误,并且错误代码具体定位也可查看。