Sentry的前端异样监控计划

Sentry的异样信息收集形式分为两种,一种为主动收集,另一种为业务我的项目中手动收集,咱们临时只钻研主动收集的形式。

异样监控收集的数据类型

首先定位到代码的instrument办法,能够看到全局主动收集的数据类型有以下几种:

  • console
  • dom
  • xhr
  • fetch
  • history
  • error
  • unhandledrejection
/** Instruments given API */function instrument(type: InstrumentHandlerType): void {  if (instrumented[type]) {    return;  }  instrumented[type] = true;  switch (type) {    case 'console': // console的信息      instrumentConsole();      break;    case 'dom':      instrumentDOM(); // 监听并记录dom上的click keyPress事件      break;    case 'xhr': // xhr申请信息      instrumentXHR();      break;    case 'fetch': // fetch申请信息      instrumentFetch();      break;    case 'history':// 浏览器行为记录(点击后退 后退按钮)      instrumentHistory();      break;    case 'error': // 全局window.onerror事件 监听js运行谬误      instrumentError();      break;    case 'unhandledrejection': // Promise 异样      instrumentUnhandledRejection();      break;    default:      logger.warn('unknown instrumentation type:', type);  }}

接下来咱们重点钻研一下 error unhandledrejection 以及 fetch xhr

window.onerror

window.onerror次要收集的是js代码运行时的全局异样.此处代码简略来说就是把原有的window.onerror包了一层,次要收集的信息有:
* msg:错误信息(字符串)。可用于HTML onerror=""处理程序中的event
* url:产生谬误的脚本URL(字符串)
* line:产生谬误的行号(数字)
* column:产生谬误的列号(数字)
* error:Error对象(对象)或 其余类型

let _oldOnErrorHandler: OnErrorEventHandler = null;/** JSDoc */function instrumentError(): void {  _oldOnErrorHandler = global.onerror;  global.onerror = function (msg: any, url: any, line: any, column: any, error: any): boolean {    triggerHandlers('error', {      column,      error,      line,      msg,      url,    });    if (_oldOnErrorHandler) {      return _oldOnErrorHandler.apply(this, arguments);    }    return false;  };}

window.unhandleRejection

当 Promise 被 reject 且没有 reject 处理器的时候,会触发 unhandledrejection 事件;

解决形式与window.onerror类似,都是包了一层

let _oldOnUnhandledRejectionHandler: ((e: any) => void) | null = null;/** JSDoc */function instrumentUnhandledRejection(): void {  _oldOnUnhandledRejectionHandler = global.onunhandledrejection;  global.onunhandledrejection = function (e: any): boolean {    triggerHandlers('unhandledrejection', e);    if (_oldOnUnhandledRejectionHandler) {      return _oldOnUnhandledRejectionHandler.apply(this, arguments);    }    return true;  };}

xhr

从上面的代码能够看出,次要对xhr 原型链上的send 以及open办法进行改写,然而须要留神的是此处并没有只收集异样信息,也不能捕捉到接口404 500等信息(需手动收集)

function instrumentXHR(): void {  // 局部代码已做删减  const xhrproto = XMLHttpRequest.prototype;  fill(xhrproto, 'open', function (originalOpen: () => void): () => void {    return function (this: SentryWrappedXMLHttpRequest, ...args: any[]): void {      const xhr = this;      const onreadystatechangeHandler = function (): void {        if (xhr.readyState === 4) {          if (xhr.__sentry_xhr__) {              xhr.__sentry_xhr__.status_code = xhr.status;            }          triggerHandlers('xhr', {            args,            endTimestamp: Date.now(),            startTimestamp: Date.now(),            xhr,          });        }      };      if ('onreadystatechange' in xhr && typeof xhr.onreadystatechange === 'function') {        fill(xhr, 'onreadystatechange', function (original: WrappedFunction): Function {          return function (...readyStateArgs: any[]): void {            onreadystatechangeHandler();            return original.apply(xhr, readyStateArgs);          };        });      } else {        xhr.addEventListener('readystatechange', onreadystatechangeHandler);      }      return originalOpen.apply(xhr, args);    };  });  fill(xhrproto, 'send', function (originalSend: () => void): () => void {    return function (this: SentryWrappedXMLHttpRequest, ...args: any[]): void {      triggerHandlers('xhr', {        args,        startTimestamp: Date.now(),        xhr: this,      });      return originalSend.apply(this, args);    };  });}

fetch

相比起xhr,fetch的数据捕捉流程就显得比拟洁净清晰得多(fetch自身是基于promise的)。咱们能够比拟容易的看出,fetch申请记录的就是申请的 method url 起始工夫 完结工夫 申请返回的信息,以及错误信息

function instrumentFetch(): void {  fill(global, 'fetch', function (originalFetch: () => void): () => void {    return function (...args: any[]): void {      const handlerData = {        args,        fetchData: {          method: getFetchMethod(args),          url: getFetchUrl(args),        },        startTimestamp: Date.now(),      };      triggerHandlers('fetch', {        ...handlerData,      });      return originalFetch.apply(global, args).then(        (response: Response) => { // 记录失常申请的信息          triggerHandlers('fetch', {            ...handlerData,            endTimestamp: Date.now(),            response,          });          return response;        },        (error: Error) => { // 记录异样申请的信息          triggerHandlers('fetch', {            ...handlerData,            endTimestamp: Date.now(),            error,          });          throw error;        },      );    };  });}

总结

毫无意外,咱们能够看出主动收集的错误信息,都是通过代理的形式,将原有的window.xx办法包裹一层,进行改写。其实在钻研之前也大略猜到了,然而毕竟集体的教训无限,很难比拟全面地理解到具体收集哪些方面的信息,这次通过sentry算是清晰了整体的脉络。