Implementation method of WeChat applet data statistics and error statistics

In some cases, we need to perform data on the behavior of some users of the small program, such as the UV, PV, etc. of a page, and statistics, the usage of a function. It is good to let the product have aware of the entire function of the product. In the web page, many of us have used Google Statistics, and there are also some third-party data statistics in the applet, such as Tencent’s MTA, etc. However, the third party’s data statistics library is either simple, and it is not necessary to charge. (Leave a poor tears.) Wait, not you pay, afraid? It is expensive to you.

Well, it’s right. However, the company team wants to achieve a complete set of its own data statistics to meet your needs. So, there is still no third party.

So, what should be statistically statistically?

Product Manager

I want to know how users enter our applet?

    The user stayed in our small program stayed longest? What is the average user stay time?
  • Do you want to know how much is the function we have recently developed?
  • I want to have some buttons in the small program to click
  • Developer

Always very difficult BUG,

    if you can know if the user ends an error, know the mobile phone model, WeChat version, network environment, page parameters, and error messages, and error messages
  • Want to know how much is our small program startup time?
  • How much is the average response time of the user ends? Which interfaces are wrong
  • We can know that TA wants to implement data statistics Function. For development, we have more concern is something wrong with the performance of the small program performance.
  • Good, here, our demand is understood. It is to achieve a set of statistics of ordinary buried points, but alsoSome special triggered events in a small program, such as Applaunch, AppHide, etc., you have to count errors.
Well, let’s take a look at how to achieve product needs

User enters a small program to get the parameter’s Scene value in the small program Onlaunch callback, so you can know how the user is Enter the applet. Small Case, I can’t get it.

Well, the first demand is realized, how do you statistically the second? How to count the residence time of a page?

This is also difficult for me, the user triggers an onshow event when entering the page. Similarly, when leaving the page (or cut the back, I only need to record the time in ONSHOW, at the same time In Onhide, I also recorded a time, and I can lose two times.

Page ({Data: {Begintime: 0, endtime: 0}, onshow: function () {// do sometying attdata ({Begintime) : new date (). getTime ()})}, onhide: function () {// do something = new date (). gettime () – this.begintime; // This is the user in this The page residence time is},})

, etc., this is indeed a need, in case the product should statistically stay the duration of stay? Then don’t we write this time every page? Is there a better way?
Ok, next is the main points of data statistics, that is, intercepting WeChat native events,This can trigger something about our statistics when a special event is triggered. At the same time, it is necessary to block the method of web request, which can get the data related to the network request. Finally, in order to be able to count the error, it is necessary to block the WeChat error.

Registration applet . Accept an Object parameter, which specifies the life cycle callback of the applet.

APP () must be called in App.js, you must call and can only call it. Otherwise, there will be unpredictable consequences.

The following is the document for the official document of the applet for the app registration method:

App ({ONLAUNCH (Options) {// Do Something Initial When Launch.}}}}}}}}}}}}}}}, Onhide () {// do somethinghen hide.}, Onerror (MSG) {Console.log (MSG)}, globaldata: ‘I am global data’}

  • What do we have to print a Hello Word when we want to ONLAUNCH? How does the method implementation?
  • Direct written in the ONLAUNCH method
  ONLAUNCH (options) {Console.log ('Hello WORLD ')}}  
Method 2:
Monkey Patch (Monkey Patch)

The monkey patch mainly has the following Used:

In the case of time, attribute, etc.

increases the function of the original unsupported function without modifying a third party code
 at runtime Add PATCH for memory instead of increasing   
in the source code of the disk, if we first print out the current timestamp in the console.log method, we can:

VAR Oldlog = console.logconsole.log = function () { (this, new date (). Gettime ()) Oldlog.Apply (this, arguments

Similar to ONLAUNCH for monkey patch

  1. VAR OLDAP = AppApp = Function (Options) {var Oldonlaunch = Options.onlaunch Options [‘Onlaunch’] = Function (T) {/ {Do something we want to do console.log (‘Hello Word ….’) // Call the original Onlaunch method Oldonlaunch .call (this, t)} // Call the original App method OldApp (options) // Imagine, the interior of the small program is called the ONLAUNCH method should be thisSample: options.onlaunch (params)} // problem, sometimes, we may not register an event, such as the onShow of the page, all, we need to judge whether the parameter has passed the corresponding method when it is replaced. Page ({OnLoad (options) {} // For this situation, we need to write VAR OldPage = pagePage = function (options) {if (options [‘onshow’]) {// If you have a registration onshow, this callback Var oldONSHOW = Options.onShow // OnShow method is sent to an object Options [‘onshow’] = function (t) {// dosomething () (this, t) }} // Call the original PAGE method. Oldpage.Apply (null, []. (arguments)) // Note: The following two writes will be reported: VM23356: 1 Options is not object: {“0”: {}} in Pages / Badge.js The problem is not found for the specific reason. // (null, arguments) // OldPage (arguments)}
  2. By the above method, we can intercept some global approaches to the App method, such as ONLAUNCH, ONSHOW, INHIDE, and PAGE registered events such as Onshow, Onhide, Onload, OnpullDownRefresh, etc. Connect events.
  3. 2. Network requestMonitor

Idea: Intercepting WeChat’s request event.

Let request = {Request: Function (e) {let success = e [0] .success, fail = e [0] .fail, begintime = smautils.getime (), EndTime = 0 // Intercept request success method E [0] .SUCCESS = Function () {endtime = smautils.getime () const performance = {type: constmap.Performance, Event: EventMap.wxRequest, URL: E [ 0] .url, status: arguments [0] .statuscode, Begin: Begintime, End: EndTime, Total: Endtime – Begintime} Smautils.loginfo (‘Success Performance:’, Performance) // What to report this // SMA .PerformanceReport (Performance) Success (this, [] (arguments))} // Intercept request failed method E [0] .fail = function () {endtime = smautils.getime () Const Performance = {TYPE: Constmap.PerformancE, Event: EventMap.wxRequest, URL: E [0] .url, Status: arguments [0] .statuscode, Begin: Begintime, End: Endtime, Total: EndTime – Begintime} Smautils.loginfo (‘Fail Performance:’, performance) // reported here do things // SMA.performanceReport (performance) fail && fail.apply (this, [] (arguments))}},} // replace micro-channel correlation properties let oldWx = wx, NEWWX = {} for (VAR P IN wx) {if (Request [P]) {let p2 = p.tostring () newwx [p2] = function () {request [p2] (arguments) // call the original WX .Request method Oldwx [p2] .apply (oldwx, []. (arguments))}} else {newwx [p] = Oldwx [p]}} // eslint-disable-next-line wx = newwx
Doubt: Why do you want to replace the entire WX object? Do not directly replace wx.request method

VAR OLDREQUEST = wx.reQuestWX.Request = Function (e) {// dosomething (); console.log (‘request interception …’) (this, e); // Call old Request method} // Result error : // TypeError: Cannot Set Property Request of [Object Object] Which Has Only A getter

3. Error monitor
  3.1 interception OneRror event in the app  

VAR OLDAP = AppApp = function (options) {var Oldonerror = Options.onerrr Options [‘OneRrr’] = function (t) {/ / Do something we want to do, console.log (‘statistics error ….’, t) // call the original Onlaunch method Oldonerror.Call (this, t)} // Call the original App method OldApp (Options

3.2 Interception Conole.Error

Console.Error = function () {var E = [] . (arguments) if (! E.LENGTH) {Return True} const currroute = smautils.getPagePath () // Statistics // SMa.errorReport ({Event: EventMap.onError, Route: Currroute, Errrmsg: arguments [0]}) Smautils.loginfo (‘Capture Error Event,’, E) Olderror.Apply (Console, E)}
   To this, we have the ability to do some data statistics we want when the life cycle or special function is called when a small program initiates a request. NS. 
I said so many of the estimates are also tired. In view of the space, the specific code is not posted here.

The final implementation of the data statistics module roughly achieved the following functions:

newspaper function
 error message   performance Data Reporting Function 
Specific report timing support configuration

supports the designated network environment to report

support statistics cache to WeChat local function

The configuration files of the statistical code are as follows:
   Const wxaconfig = {Project: 'myminiprogram', // project name Trackurl: '', // Backstage Data Statistics Interface ERRORURL: '', // Backstage Error Online PerformanceURL: '', // Background Performance News Interface Version: '0.1 ', prefix:' _wxa_ ', priority: [' TRACK ',' PErformance ',' error '], // Send the priority of the request, send USSTORAGE: TRUE, // if it is turned on whether to open the Storage Cache Debug: false, // Whether to turn on debug (display log) Autotrack: true, / / Automatically report onshow, onhide, sharing, etc. Built-in event errorReport: false, // Do not open error PerformReport: false, // Interface performance Report maxReportnum: 20, // Report the maximum number of rats INTERVALTIME: 15, / / The time interval, the unit S, only when the timing report is valid. NetworkList: ['WiFi', '4G', '3G'], // Allowed Network Environment Opportunity: 'PageHide' // PageHide, AppHide, RealTime (Realmly Report), Timing (Timed on) reported, four Option 1} Export Default WxAconfig 
When reported, the data structure reported in the reporting data is larger as such:

The project has Transfer to Github -> GitHub Transport Door-WXA
  The above is all of this article, I hope to help everyone, I hope everyone will support Tumi Cloud.  
© Copyright Notice
Just support it if you like
comment Grab the couch

Please log in to comment