Build front-end monitoring System (ii) JS error log Collection Chapter

Source: Internet
Author: User

=================== Code Show ================

Monitoring System Address: Demo Address

page probe code: GitHub address

Analyze the backend address:   GitHub address

Display platform Address: GitHub address

=================== Code Show ================

  For front-end applications, the occurrence of JS errors directly affects the quality of the front-end application. The monitoring of JS Anomaly is an important link in the whole front-end monitoring system. So how to do the JS error monitoring it? How do we analyze the JS errors that we have compiled? How should the results of the analysis be presented? These issues will directly affect the ability to monitor and divide valuable data.

  first of all , we should have a general understanding of JS Error situation, so as to be able to timely understand the health of the front-end project. So we need to analyze some of the necessary data.

such as: For a period of time, the use of JS Error trends (chart charts), the rate of JS errors, JS errors on the PC side of the probability, JS errors on the iOS side of the probability, JS errors on the Android side of the probability, and JS error classification.

  then , we go to the JS error in the detailed analysis, assist us to troubleshoot the location of the error and the cause of the error.

such as: JS error type, JS error message, JS error stack, JS error occurred in the location and the location of the code, the probability of JS error, browser type, version number, device model, and other ancillary information

One, JS Error monitoring function (data preview)

  

In order to get this data, we need to analyze it when we upload it. In many log analyses, many fields and functions are duplicated, so they should be encapsulated.

//set common properties for the Log object class  functionSetcommonproperty () { This. Happentime =NewDate (). GetTime ();//Log Occurrence Time     This. Webmonitorid = web_monitor_id;//unique identity used to differentiate an app (one item)     This. Simpleurl = Window.location.href.split ('? ') [0].replace (' # ', ');//URL of the page     This. Customerkey = Utils.getcustomerkey ();//used to differentiate users, corresponding unique identities, and to clean up local data after failure     This. Pagekey = Utils.getpagekey ();//used to differentiate the page, corresponding to the unique identity, each new page corresponds to a value     This. DeviceName =Device_info.devicename;  This. OS = Device_info.os + (device_info.osversion? "" + Device_info.osversion: "");  This. Browsername =Device_info.browsername;  This. browserversion =device_info.browserversion; //Todo location information, pending processing     This. Monitorip = "";//the IP address of the user     This. Country = "China";//User Country     This. Province = "";//User Province     This. City = "";//The city where the user resides    //user-defined information, initiated by the developer, facilitates accurate positioning on the line     This. UserId =User_info.userid;  This. Firstuserparam =User_info.firstuserparam;  This. Seconduserparam =User_info.seconduserparam; }  //JS error log, inherited from the log base class Monitorbaseinfo  functionJavascripterrorinfo (Uploadtype, errormsg, Errorstack) {setcommonproperty.apply ( This);  This. Uploadtype =Uploadtype;  This. errormessage =encodeURIComponent (errormsg);  This. Errorstack =Errorstack;  This. Browserinfo =Browser_info; } Javascripterrorinfo.prototype=NewMonitorbaseinfo ();

Encapsulates a Jserror object Javascripterrorinfo to save the JS error generated on the page. Where Setcommonproperty is used to set common properties for all log objects.

1) Rewrite the Window.onerror method, we are well-known, the monitoring JS error must be inseparable from it, some people on his test test introduction feeling is also more intentions

2) Rewrite the Console.error method, why to rewrite this method, I can not give a clear answer, if the app first injected into the browser JS code error, Window.onerror is unable to monitor, so can only be captured in this way, there may be a better way to wait for Window.on After the error succeeds, this method no longer needs to be used.

Below is the start JS error monitoring code

/** * Page JS error monitoring*/  functionRecordjavascripterror () {//rewrite the Console.error to capture more comprehensive error messages    varOlderror =Console.error; Console.error=function () {      //The length of the arguments is 2 o'clock, which is the time for error escalation.      //if (Arguments.length < 2) return;      varErrorMsg = arguments[0] && arguments[0].message; varURL =web_location; varlinenumber = 0; varColumnNumber = 0; varErrorobj = arguments[0] && arguments[0].stack; if(!errorobj) Errorobj = arguments[0]; //if the onerror rewrite succeeds, there's no need to escalate here.!jsmonitorstarted &&siftandmakeupmessage (errormsg, URL, linenumber, ColumnNumber, errorobj); returnolderror.apply (console, arguments);    }; //rewrite the onerror for jserror monitoringWindow.onerror =function(errormsg, URL, linenumber, ColumnNumber, errorobj) {jsmonitorstarted=true; varErrorstack = errorobj? Errorobj.stack:NULL;    Siftandmakeupmessage (errormsg, URL, linenumber, ColumnNumber, Errorstack);    }; functionsiftandmakeupmessage (origin_errormsg, Origin_url, Origin_linenumber, Origin_columnnumber, ORIGIN_ERROROBJ) {varErrorMsg = origin_errormsg? Origin_errormsg: "; varErrorobj = origin_errorobj? Origin_errorobj: "; varErrorType = ""; if(errormsg) {varErrorstackstr =json.stringify (errorobj) ErrorType= Errorstackstr.split (":") [0].replace (' "'," ""); }      varJavascripterrorinfo =NewJavascripterrorinfo (Js_error, ErrorType + ":" +errormsg, errorobj);    Javascripterrorinfo.handleloginfo (Js_error, javascripterrorinfo);  }; };

OK, the error log has, how to calculate the error rate?

  js Error Rate = JS Error number (one access page, all JS errors are counted once)/PV (Pc,ios,android platform)

So we need to write down the PV record of the page.

 //User Access behavior log (PV)    functionCUSTOMERPV (Uploadtype, Loadtype, loadtime) {setcommonproperty.apply ( This);  This. Uploadtype =Uploadtype;  This. Loadtype = Loadtype;//To differentiate the first load       This. loadtime = Loadtime;//Load Time} customerpv.prototype=NewMonitorbaseinfo (); /** * Add a timer to upload the data * 3 seconds to make a URL change detection * 15 seconds to check the data and upload*/    varDefaultLocation = Window.location.href.split ('? ') [0].replace (' # ', ' '); varTimecount = 0; SetInterval (function () {      //if it's a single page app, just change the URL      varWeblocation = Window.location.href.split ('? ') [0].replace (' # ', ' '); //If the URL changes, record the updated URL as defaultLocation and reset the Pagekey      if(DefaultLocation! =weblocation)        {RECORDPV (); DefaultLocation=weblocation; }      //Loop 5 to upload at a later time      if(Timecount >= 5) {        varLoginfo = Localstorage[ele_behavior] | | "" +Localstorage[js_error]|| "" +LOCALSTORAGE[CUSTOMER_PV]|| ""; if(loginfo) {Utils.ajax ("POST", Http_upload_log_info, {loginfo:loginfo},function(res) {//when the upload is complete, clear the local record            if(Res.code = = 200) {Localstorage[ele_behavior]= ""; Localstorage[js_error]= ""; LOCALSTORAGE[CUSTOMER_PV]= ""; }})} Timecount= 0; } Timecount++; }, 3000);

  The above code I used the timer, about 3 seconds to do a URL change check, 15 to check the data, if there is data to upload, and empty the last data. Why use a timer, because in a single page application, the change of Routing and address bar can not be monitored, I really did not think of a particularly good way to monitor, so in this way, if someone has a better way, please leave me a message, thank you

To this, has collected the JS error log most of the information, just to upload it, storage, and then analyze the display, you can see the preview of JS error message, so we go to deploy the background code.

Next chapter: Building the front-end monitoring System (iii) NODEJS Server Deployment Chapter

  

In order to upload this data to our servers, we can't always use XMLHttpRequest to send AJAX requests.

So we need to encapsulate a simple Ajax

/** * * @param method request type (UPPERCASE) get/post * @param URL request URL * @param param request parameter * @param SUCC Esscallback Successful callback method * @param failcallback Failure callback method*/     This. Ajax =function(method, URL, param, successcallback, failcallback) {varxmlHttp = window. XMLHttpRequest?NewXMLHttpRequest ():NewActiveXObject (' Microsoft.XMLHTTP '); Xmlhttp.open (method, URL,true); Xmlhttp.setrequestheader (' Content-type ', ' application/x-www-form-urlencoded '); Xmlhttp.onreadystatechange=function () {        if(Xmlhttp.readystate = = 4 && xmlhttp.status = 200) {          varres =Json.parse (Xmlhttp.responsetext); typeofSuccesscallback = = ' function ' &&Successcallback (RES); } Else {          typeofFailcallback = = ' function ' &&Failcallback ();      }      }; Xmlhttp.send ("Data=" +json.stringify (param)); }

Build front-end monitoring System (ii) JS error log Collection Chapter

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.