程序员

Sentry系列一——React接入Sentry完整教程

2022-11-11  本文已影响0人  翔子丶

原文链接:http://wangxiang.website/docs/work/sentry.html

Sentry介绍与使用

简介

Sentry 是跨平台的应用程序监控,专注于错误报告。GitHub官方网站

Sentry 翻译过来是「哨兵」的意思,可以监控程序代码中出现的报错问题,生成issue,通过查看issue快速定位到问题发生的位置。

使用

  1. 安装
npm install --save @sentry/react @sentry/tracing
  1. 配置

原理

Javascript代码发生错误后,Javascript引擎会抛出一个Error对象,并触发window.onerror事件,Sentry正是对window.onerror进行重写,实现错误监控的逻辑,并添加了很多信息帮助错误定位,并对错误进行滚跨浏览器的兼容等

接入SourceMap

使用Sentry的webpack插件配置sourceMap,在构建的时候自动上传到Sentry,如果不上传SourceMap有些问题不好定位<br />
Sentry一共提供了三种上传source map的方式

Sentry-cli

文档

使用API上传

文档

使用webpack plugins

  1. 安装@sentry/webpack-plugin
npm install --save-dev @sentry/webpack-plugin
  1. 项目根目录添加.sentryclirc文件
[auth]
token = ef5b031a00964f3c8f8ccbca07bb03c1d950be4b33f24ff

[defaults]
url = https://sentry-monitor.xxx.com/
org = xxx
project = xxx
  1. 配置webpack
const SentryWebpackPlugin = require("@sentry/webpack-plugin");
 
module.exports = {
  // other webpack configuration
  devtool: 'source-map',
  // 将 Webpack 插件设置为最后运行的插件  否则插件收到的 source maps 可能不是最终的
  plugins: [
    new SentryWebpackPlugin({
      release:"v1.0.1",
      include: ".", 
      ignore: ["node_modules", "webpack.config.js"],
      configFile: "sentry.properties",
    }),
  ],
};

在sentry上就会有对应项目的 Source Map 文件;(在settings -> projects -> xxx -> Source Maps)

sentry.jpg
  1. 测试
sentryerror.jpg

在webpack的afterEmit钩子(在生成文件到output目录之后执行)中获取打包后的文件,过滤出文件类型为/\.js$|\.map$/结尾的文件上传到对应的sentry服务器

// upload sourcemaps
apply(compiler) {
  // afterEmit在生成文件到output目录之后执行
  compiler.hooks.afterEmit.tapAsync(this.name, async (compilation, callback) => {
    const files = this.getFiles(compilation);
    try {
      await this.createRelease();
      await this.uploadFiles(files);
      console.info('\n\u001b[32mUpload successfully.\u001b[39m\n');
    } catch (error) {
      // todo
    }
    callback(null);
  });
}
 // 获取需要上传的文件
 getFiles(compilation) {
   // 通过 compilation.assets 获取我们需要的文件信息,格式信息
      // compilation.assets {
      // 'bundle.js': SizeOnlySource { _size: 212 },
      // 'bundle.js.map': SizeOnlySource { _size: 162 }
      // }
  return Object.keys(compilation.assets)
    .map((name) => {
    if (this.isIncludeOrExclude(name)) {
      return { name, filePath: this.getAssetPath(compilation, name) };
    }
    return null;
  })
    .filter(Boolean);
}
 // 获取文件的绝对路径
 getAssetPath(compilation, name) {
    return path.join(compilation.getPath(compilation.compiler.outputPath), name.split('?')[0]);
 }
 // 获取文件的绝对路径
 getAssetPath(compilation, name) {
    return path.join(compilation.getPath(compilation.compiler.outputPath), name.split('?')[0]);
 }
 // 上传文件
 async uploadFile({ filePath, name }) {
   console.log(filePath);
   try {
     await request({
       url: `${this.sentryReleaseUrl()}/${this.release}/files/`, // 上传的sentry路径
       method: 'POST',
       auth: {
         bearer: this.apiKey,
       },
       headers: {},
       formData: {
         file: fs.createReadStream(filePath),
         name: this.filenameTransform(name),
       },
     });
   } catch (e) {
     console.error(`uploadFile failed ${filePath}`);
   }
 }

webpack钩子

对比

与其他的npm下载量对比

上一篇 下一篇

猜你喜欢

热点阅读