Vue3引入Sentry错误监测系统

981 阅读2分钟
Sentry的使用

step1.在docs.sentry.io/注册自己的账号

step2.创建项目

step3.在你的项目中安装Sentry

npm install --save @sentry/vue

step4.在Vue项目的main.ts中引用Sentry提供的初始化代码

import { createApp } from 'vue'
import * as Sentry from '@sentry/vue'

const app = createApp(App)
Sentry.init({
  app,
  dsn: 'https://3eee12a6b50947f6bebd10c417117fc8@o4505584881696768.ingest.sentry.io/4505589443723264',
  integrations: [
    new Sentry.BrowserTracing({
      // Set 'tracePropagationTargets' to control for which URLs distributed tracing should be enabled
      tracePropagationTargets: ['localhost', 'https:yourserver.io/api/'],
      routingInstrumentation: Sentry.vueRouterInstrumentation(router),
    }),
    new Sentry.Replay(),
  ],
  // Performance Monitoring
  tracesSampleRate: 1.0, // Capture 100% of the transactions, reduce in production!
  // Session Replay
  replaysSessionSampleRate: 0.1, // This sets the sample rate at 10%. You may want to change it to 100% while in development and then sample at a lower rate in production.
  replaysOnErrorSampleRate: 1.0, // If you're not already sampling the entire session, change the sample rate to 100% when sampling sessions where errors occur.
})

至此配置完成。

Sentry测试

step1.本地安装Http-server服务,为了能够在本地开启dist文件夹web服务,苹果电脑为例

sudo npm install http-server -g

step2.VUE项目打包

npm run build

step3.进入dist文件夹,开启端口为8888的web服务

http-server -p 8888

step4.运行项目,故意写错变量,这个时候就可以收到邮件信息和错误信息了

配置sourcemap

它的功能是可以在线上发生错误时,可以定位到源代码的错误位置,根据采用的JS压缩工具选择不同的方式进行配置sourcemap。

Uploading Source Maps for Node.js

我们这里采用Vite,可以参考Vite for Node.js。这里可以采用两种方式进行配置,一种是自动上次,一种是手动上传,我以手动上传为例。

step1.安装sentry插件

npm install @sentry/vite-plugin --save-dev

step2.配置Vite

import { defineConfig } from 'vite'
import { sentryVitePlugin } from '@sentry/vite-plugin'

export default defineConfig({
  plugins: [
    sentryVitePlugin({
      org: 'liuyufang', // 组织名称
      project: 'javascript-vue3', // 项目名称
      authToken: process.env.SENTRY_AUTH_TOKEN // 项目token
    })
  ],
  build: {
    sourcemap: true
  }
})

至此配置完成。

sourcemap测试

step1.打包项目时,sentryVite插件就会自动上传sourcemap文件到sentry后台。

npm run build

step2.进入dist文件夹,开启本地服务

cd dist
http-server -p 8888

step3.控制台查看报错信息

step4.sentry后台也显示了报错信息,并且指向源代码

文档:API Reference