前端项目集成sentry

1,547 阅读1分钟

初始化Sentry

import * as Sentry from '@sentry/vue';
Sentry.init({
  Vue,
  dsn: "https://****2c7e6e9b102****@sentry-inc.***.***.com/160",
})

dns在Sentry平台上创建项目后就会有

配置sourcemap

const { sentryWebpackPlugin } = require("@sentry/webpack-plugin");

configureWebpack: {
    devtool: 'source-map',
    resolve: {
      alias: {
        '@': resolve('src')
      }
    },
    plugins: [
      // Put the Sentry Webpack plugin after all other plugins
      sentryWebpackPlugin({
        authToken: '****28e2e47cc1820d95a4aedb352899a1****',
        sourcemap: {
          urlPrefix: '~/test-project/' //~/只代表域名
        },
        org: "sentry",
        project: "test-project",
        url: "https://sentry-inc.***.***.com/",
      }),
    ],
  },

还可以使用插件unplugin-sentry配置sourcemap

npm i unplugin-sentry -D

// webpack config
const unpluginSentry = require('unplugin-sentry/webpack').default;

plugins: [
	unpluginSentry({
      url: 'https://sentry-inc.***.***.***//',
      org: 'sentry',
      project: 'sentry项目名字',
      authToken: '创建的authToken', 
      publish: env !== 'development', // 默认本地运行时不发布sourceMap
      cleanLocal: true, // 清空本地sourcemap
      sourcemap: {
        urlPrefix: '~/'
      },
      release: release,
      deploy: {
        env: environment
      }
    })
]

sentry init时读取配置

import * as sentryMeta from 'virtual-unplugin-sentry-runtime';
import * as Sentry from '@sentry/vue';

try {
    // 初始化sentry
    // eslint-disable-next-line no-undef
    Sentry.init({
	  Vue,
      dsn: 'dsn',
      // eslint-disable-next-line no-undef
      release: sentryMeta.RELEASE,
      environment: sentryMeta.ENV,
      // eslint-disable-next-line no-undef
      integrations: [new Sentry.BrowserTracing({
      	routingInstrumentation: Sentry.vueRouterInstrumentation(router),
      	tracePropagationTargets: []
      })],
      // Set tracesSampleRate to 1.0 to capture 100%
      // of transactions for performance monitoring.
      // We recommend adjusting this value in production
      // eslint-disable-next-line no-undef
      tracesSampleRate: environment === 'production' ? 0.6 : 1
    });
  } catch (err) {
    console.log(`sentry 初始化失败${err}`);
  }

通过插件读取打包时的release和env,保证两边一致才能匹配sourcemap

authToken的生成

企业微信截图_162911e3-91b3-416f-bcfc-e90c784c08fe.png

企业微信截图_9c3d4545-89e4-4dda-9391-39b5160ee662.png

企业微信截图_3efbda08-90c4-4423-8caf-2c133c1e5724.png

没有使用sourcemap时

企业微信截图_d8dfd5aa-04f5-4dd9-820b-51eb0870540d.png

使用sourcemap后

企业微信截图_32a718f6-3bd5-4d81-85e2-87360af952d9.png

sourcemap配置正确, npm run build打包会提示相应的信息

企业微信截图_4f6756d5-01a9-44ec-8a00-41c9738d1189.png

企业微信截图_fa36f25b-e2c2-4388-9272-7337b6a6f42d.png

打包报错

[sentry-webpack-plugin] Warning: No auth token provided. Will not upload source maps. Please set the authToken option. You can find information on how to generate a Sentry auth token here: docs.sentry.io/api/auth/