vieyahn2017 / jsup

0 stars 1 forks source link

raven.js - 浏览器的错误记录监控 #20

Open vieyahn2017 opened 1 year ago

vieyahn2017 commented 1 year ago

raven https://github.com/getsentry/sentry-javascript

vieyahn2017 commented 1 year ago

调测 之 https://blog.csdn.net/qq_36644198/article/details/131723549 谷歌浏览器的本地替换js等文件使用体验

vieyahn2017 commented 1 year ago

/! Raven.js 3.26.2 (0c2973a) | github.com/getsentry/raven-js /

vieyahn2017 commented 1 year ago

t = Object.keys(Raven)

Raven

[ "_hasJSON", "_hasDocument", "_hasNavigator", "_lastCapturedException", "_lastData", "_lastEventId", "_globalServer", "_globalKey", "_globalProject", "_globalContext", "_globalOptions", "_fetchDefaults", "_ignoreOnError", "_isRavenInstalled", "_originalErrorStackTraceLimit", "_originalConsole", "_originalConsoleMethods", "_plugins", "_startTime", "_wrappedBuiltIns", "_breadcrumbs", "_lastCapturedEvent", "_location", "_lastHref", "_backoffDuration", "_backoffStart", "noConflict", "Client", "_dsn", "_globalSecret", "_globalEndpoint", "_promiseRejectionHandler", "_originalFunctionToString", "_keypressTimeout" ]

vieyahn2017 commented 1 year ago

在raven.min.js

tt = Object.keys(Raven)

[ "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "ka", "la", "noConflict", "Client", "H", "I", "K", "T", "da", "aa" ]

vieyahn2017 commented 1 year ago

maps = {} tt.map((item,index) => {maps[item]=t[index]});

maps

{ "a": "_hasJSON", "b": "_hasDocument", "c": "_hasNavigator", "d": "_lastCapturedException", "e": "_lastData", "f": "_lastEventId", "g": "_globalServer", "h": "_globalKey", "i": "_globalProject", "j": "_globalContext", "k": "_globalOptions", "l": "_fetchDefaults", "m": "_ignoreOnError", "n": "_isRavenInstalled", "o": "_originalErrorStackTraceLimit", "p": "_originalConsole", "q": "_originalConsoleMethods", "r": "_plugins", "s": "_startTime", "t": "_wrappedBuiltIns", "u": "_breadcrumbs", "v": "_lastCapturedEvent", "w": "_location", "x": "_lastHref", "ka": "_backoffDuration", "la": "_backoffStart", "noConflict": "noConflict", "Client": "Client", "H": "_dsn", "I": "_globalSecret", "K": "_globalEndpoint", "T": "_promiseRejectionHandler", "da": "_originalFunctionToString", "aa": "_keypressTimeout" }

vieyahn2017 commented 1 year ago

Raven._globalOptions.autoBreadcrumbs

{ "xhr": true, "console": true, "dom": true, "location": true, "sentry": true }

vieyahn2017 commented 1 year ago

  /**
   * Instrument browser built-ins w/ breadcrumb capturing
   *  - XMLHttpRequests
   *  - DOM interactions (click/typing)
   *  - window.location changes
   *  - console
   *
   * Can be disabled or individually configured via the `autoBreadcrumbs` config option
   */
  _instrumentBreadcrumbs: function() {
    var self = this;
    var autoBreadcrumbs = this._globalOptions.autoBreadcrumbs;
    this._originalConsole.log(autoBreadcrumbs);

    autoBreadcrumbs = {
        "xhr": false,
        "console": false,
        "dom": true,
        "location": true,
        "sentry": true
    }
    this._originalConsole.log(autoBreadcrumbs);
    this._globalOptions.autoBreadcrumbs = autoBreadcrumbs;

    ...

  }

说的可配置,但是我在console配置不了,大概是说的只有服务器端install的时候可以config吧

vieyahn2017 commented 1 year ago

Raven._globalOptions.autoBreadcrumbs.console = false Raven._globalOptions.autoBreadcrumbs.xhr= false

Raven._globalOptions.captureUnhandledRejections = false Raven._globalOptions.collectWindowErrors = false

真正的拦截,依然生效

vieyahn2017 commented 1 year ago

console的相关源码


    if (autoBreadcrumbs.console && 'console' in _window && console.log) {
      // console
      var consoleMethodCallback = function(msg, data) {
        self.captureBreadcrumb({
          message: msg,
          level: data.level,
          category: 'console'
        });
      };

      each(['debug', 'info', 'warn', 'error', 'log'], function(_, level) {
        wrapConsoleMethod(console, level, consoleMethodCallback);
      });
    }
  },
vieyahn2017 commented 1 year ago

fetch的源码


    if (autoBreadcrumbs.xhr && supportsFetch()) {
      fill(
        _window,
        'fetch',
        function(origFetch) {
          return function() {
            // preserve arity
            // Make a copy of the arguments to prevent deoptimization
            // https://github.com/petkaantonov/bluebird/wiki/Optimization-killers#32-leaking-arguments
            var args = new Array(arguments.length);
            for (var i = 0; i < args.length; ++i) {
              args[i] = arguments[i];
            }

            var fetchInput = args[0];
            var method = 'GET';
            var url;

            if (typeof fetchInput === 'string') {
              url = fetchInput;
            } else if ('Request' in _window && fetchInput instanceof _window.Request) {
              url = fetchInput.url;
              if (fetchInput.method) {
                method = fetchInput.method;
              }
            } else {
              url = '' + fetchInput;
            }

            // if Sentry key appears in URL, don't capture, as it's our own request
            if (url.indexOf(self._globalKey) !== -1) {
              return origFetch.apply(this, args);
            }

            if (args[1] && args[1].method) {
              method = args[1].method;
            }

            var fetchData = {
              method: method,
              url: url,
              status_code: null
            };

            return origFetch
              .apply(this, args)
              .then(function(response) {
                fetchData.status_code = response.status;

                self.captureBreadcrumb({
                  type: 'http',
                  category: 'fetch',
                  data: fetchData
                });

                return response;
              })
              ['catch'](function(err) {
                // if there is an error performing the request
                self.captureBreadcrumb({
                  type: 'http',
                  category: 'fetch',
                  data: fetchData,
                  level: 'error'
                });

                throw err;
              });
          };
        },
        wrappedBuiltIns
      );
    }
vieyahn2017 commented 1 year ago

sentry 的breadcrumb功能

https://raven-js.readthedocs.io/en/stable/

https://docs.sentry.io/clients/javascript/usage/#raven-js-recording-breadcrumbs

https://docs.sentry.io/clients/javascript/

vieyahn2017 commented 1 year ago

raven_test_1.js


    let analysis2_fetch = async function (url) {
        const response = await fetch(url);
        // const data = (await response.json()).data;
        const data = await response.json();
        return data;
    }

    let analysis2 = async function(){
        console.log("xxx unsupported.")

        const examResultId = "3333";
        console.log(examResultId);
        var protocol = "http";
        const url_XXX = "://xxx.com/yyy/" + examResultId;
        var answerDetails = null;
        try {
            answerDetails = await analysis2_fetch(protocol + url_XXX);
        } catch(e) {
            if (e.message == "Failed to fetch") {
                protocol = "https";
                answerDetails = await analysis2_fetch(protocol + url_XXX);
            } else {
                console.log(e);
                return;
            }
        }
        if(!answerDetails) {
            console.log("please assign XXX");
            return;
        }
        console.log(answerDetails);
    }

    // analysis2();

    let analysis2_callback = function () {
        analysis2();
    }

    if (document.querySelector(".candidates-info") != null) {
        document.querySelector(".candidates-info").onclick = analysis2_callback;
    }

结果,可以看到,console和xdr都被raven拦截

xxx unsupported.
raven.min.js:58 3333
raven.min.js:1536 Mixed Content: The page at '****' was loaded over HTTPS, but requested an insecure resource 'http://xxx.com/yyy/3333'. This request has been blocked; the content must be served over HTTPS.
(anonymous) @ raven.min.js:1536
analysis2_fetch @ VM557:2
analysis2 @ VM557:17
analysis2_callback @ VM557:37
raven.min.js:1536     GET https://xxx.com/yyy/3333 net::ERR_SSL_PROTOCOL_ERROR
(anonymous) @ raven.min.js:1536
analysis2_fetch @ VM557:2
analysis2 @ VM557:21
await in analysis2 (async)
analysis2_callback @ VM557:37
raven.min.js:1536     Uncaught (in promise) TypeError: Failed to fetch
    at raven.min.js:1536:16
    at analysis2_fetch (<anonymous>:2:32)
    at analysis2 (<anonymous>:21:39)
(anonymous) @ raven.min.js:1536
analysis2_fetch @ VM557:2
analysis2 @ VM557:21
await in analysis2 (async)
analysis2_callback @ VM557:37
vieyahn2017 commented 1 year ago

raven_test_2.js

    let my_console_log = console.log;

    let analysis2_fetch = async function (url) {
        const response = await fetch(url);
        // const data = (await response.json()).data;
        const data = await response.json();
        return data;
    }

    let analysis2 = async function(){
        my_console_log("xxx unsupported.")

        const examResultId = "3333";
        my_console_log(examResultId);
        var protocol = "http";
        const url_XXX = "://xxx.com/yyy/" + examResultId;
        var answerDetails = null;
        try {
            answerDetails = await analysis2_fetch(protocol + url_XXX);
        } catch(e) {
            if (e.message == "Failed to fetch") {
                protocol = "https";
                answerDetails = await analysis2_fetch(protocol + url_XXX);
            } else {
                my_console_log(e);
                return;
            }
        }
        if(!answerDetails) {
            my_console_log("please assign XXX");
            return;
        }
        my_console_log(answerDetails);
    }

    // analysis2();

    let analysis2_callback = function () {
        analysis2();
    }

    if (document.querySelector(".candidates-info") != null) {
        document.querySelector(".candidates-info").onclick = analysis2_callback;
    }

    let hide_raven_console = function () {
        if (!Raven) {
            return;
        }
        console.dir("raven is installed, use my console log func.")
        // my_console_log = console.dir; // 不支持格式化和多参数
        my_console_log = console.table;
    }

    hide_raven_console();

console的暂时屏蔽了,xdr的还在


undefined
VM561:11 xxx unsupported.
VM561:14 3333
raven.min.js:1536 Mixed Content: The page at '***' was loaded over HTTPS, but requested an insecure resource 'http://xxx.com/yyy/3333'. This request has been blocked; the content must be served over HTTPS.
raven.min.js:1536 
 GET https://xxx.com/yyy/3333 net::ERR_SSL_PROTOCOL_ERROR
raven.min.js:1536 
 Uncaught (in promise) TypeError: Failed to fetch
    at raven.min.js:1536:16
    at analysis2_fetch (<anonymous>:4:32)
    at analysis2 (<anonymous>:24:39)
vieyahn2017 commented 1 year ago
Raven.__proto__.config23 = function() {
    var self = this;
    var globalOptions = self._globalOptions;
    var autoBreadcrumbs = self._globalOptions.autoBreadcrumbs;
    autoBreadcrumbs.console = false;
    autoBreadcrumbs.xhr = false;

    console.log("2333");
    return self;
}

Raven.config23() // 不行

vieyahn2017 commented 1 year ago

Raven._restoreConsole

Raven._restoreConsole() // 可以 Raven.S(); // raven.min.js压缩后的函数名字

vieyahn2017 commented 1 year ago

最新恢复console的方式


    this.hide_raven_console = function () {
        if (!window.Raven) {
            return;
        }
        if (Raven._restoreConsole !== undefined) {
            Raven._restoreConsole();
        } else {
            Raven.S();  // raven.min.js压缩后的函数名字
        }
        // 可以通过 Raven.u || Raven._breadcrumbs 查看被加入面包屑的对象
    }
vieyahn2017 commented 1 year ago

之前的误区 Raven._breadcrumbs 里的数据,就是向后台sentry发送的数据! 真正发起请求的函数是 _makeRequest