The monitoring SDK provides methods that are used to report data and modify SDK configurations.

Methods in this topic

api()

You can call the api() method to report the success rate of API calls on a page.

By default, the SDK listens to JavaScript and XML (AJAX) requests on the page and calls this method to report data. If data on the page is requested by using JSON with Padding (JSONP) or other custom tools such as the client SDK, you can call the api() method in the data request for manual reporting.

Note To call this method, we recommend that you set the disableHook parameter to true in the SDK configurations. For more information, see disableHook.

Syntax of api():

__bl.api(api, success, time, code, msg, begin, traceId, sid)
Or
__bl.api({api: xxx, success: xxx, time: xxx, code: xx, msg: xx, begin: xx, traceId: xx, sid: xx})
Table 1. Request parameters of api()
Parameter Type Description Required Default value
api String The name of the method. Yes N/A
success Boolean Specifies whether the call is successful. Yes N/A
time Number The amount of time consumed by the call. Yes N/A
code String/Number The response code. No ''
msg String The response information. No ''
begin Number The timestamp when the API call started. No ''
traceId String The value of the EagleEye-TraceID header. No ''
sid String The value of the EagleEye-SessionID header. No ''

Example of api():

var begin = Date.now(),
    url = '/data/getTodoList.json',
    traceId = window.__bl && __bl.getTraceId('EagleEye-TraceID'),
    sid = window.__bl && __bl.getSessionId('EagleEye-SessionID');
// Note: Specify the EagleEye-TraceID and EagleEye-SessionID headers in the request.
fetch(url, {
    headers: {
        'EagleEye-TraceID': traceId,
        'EagleEye-SessionID': sid
    }
}).then(function (result) {
    var time = Date.now() - begin;
    // Reports that the call is successful.
    window.__bl && __bl.api(url, true, time, result.code, result.msg, begin, traceId, sid);
    // do something ....
}).catch(function (error) {
    var time = Date.now() - begin;
    // Reports that the call fails.
    window.__bl && __bl.api(url, false, time, 'ERROR', error.message, begin, traceId, sid);
    // do something ...
});    

[Back to the top]

error()

You can call the error() method to report JavaScript (JS) errors or exceptions that you want to capture on a page.

Generally, the SDK listens to global errors on the page and calls this method to report exceptions. However, due to the same-origin policy of the browser, error details are usually out of reach. In this case, you must manually report such errors.

Syntax of error():
__bl.error(error, pos)
Table 2. Request parameters of error()
Parameter Type Description Required Default value
error Error The JS error object. Yes N/A
pos Object The location where the error occurs. The location contains the following three attributes. No N/A
pos.filename String The name of the file where the error occurs. No N/A
pos.lineno Number The number of the line where the error occurs. No N/A
pos.colno Number The number of the column where the error occurs. No N/A
Example 1 of error(): Listen to and report JS errors on the page.
window.addEventListener('error', function (ex) {
    // Event parameters usually contain location information. 
    window.__bl && __bl.error(ex.error, ex);
});            
Example 2 of error(): Report a custom error.
window.__bl && __bl.error(new Error('A custom error occurs.'), {
    filename: 'app.js', 
    lineno: 10, 
    colno: 15
});            
Example 3 of error(): Report a custom error.
__bl.error({name:'CustomErrorLog',message:'this is an error'}, {
    filename: 'app.js', 
    lineno: 10, 
    colno: 15
});           

[Back to the top]

speed()

You can call the speed() method to report the amount of time consumed by some custom events on a page.

Syntax of speed():
__bl.speed(point, time)
Table 3. Request parameters of speed()
Parameter Type Description Required Default value
point Enum The keyword used to measure the page speed. Valid values: s0 to s10. Yes N/A
time Number The amount of time consumed, which is from the time when the page starts to be loaded to the current time by default. Unit: ms. No Date.now() - startTime
Example of speed():
__bl.speed('s0');
__bl.speed('s1', 1024);

[Back to the top]

sum()

You can call the sum() method to customize the logs to be reported. The logs are used to count how many times a specific event occurs in a business scenario. You can view the following data reported by calling the sum() method on the Custom Statistics page:
  • Trend chart of custom events
  • Page views (PVs) and unique visitors (UVs) of an event
  • Dimension distribution information

Syntax of sum():

__bl.sum(key, value)
Table 4. Request parameters of sum()
Parameter Type Description Required Default value
key String The name of the event. Yes N/A
value Number The number of reported items at a time. No 1
Example of sum():
__bl.sum('event-a');
__bl.sum('event-b', 3);

[Back to the top]

avg()

You can call the avg() method to customize the logs to be reported. The logs are used to count how many times a specific event occurs on average in a business scenario. You can view the following data reported by the avg() method on the Custom Statistics page:
  • Trend chart of custom events
  • PVs and UVs of an event
  • Dimension distribution information
Syntax of avg():
__bl.avg(key, value)
Table 5. Request parameters of avg()
Parameter Type Description Required Default value
key String The name of the event. Yes N/A
value Number The number of reported items. No 0
Example of avg():
__bl.avg('event-a', 1);
__bl.avg('event-b', 3);

[Back to the top]

resource()

You can call the resource() method to manually report resource loading data.

Syntax of resource():
__bl.resource(data, sampling)
Table 6. Request parameters of resource()
Parameter Type Description Required Default value
data Object The data to be reported. Yes N/A
sampling String The sample rate. No 1
The data parameter contains the following fields:
  • begin: the timestamp when the page starts to be fetched.
  • dom: the amount of time consumed for document object model (DOM) resolution, which is calculated by using the following formula: domInteractive - responseEnd.
  • load: the amount of time consumed to completely load the page, which is calculated by using the following formula: loadEventStart - fetchStart.
  • res: the resource loading data to be reported. The value is of the ARRAY type. You can call the performance.getEntriesByType('resource') method to obtain the data.
  • dl: the URL of the page.
Note
  • If you want to manually report resource loading data, you must disable automatic reporting by specifying sendResource: false in the SDK configurations. Otherwise, resource loading data may be reported multiple times during a page view. This results in duplicate information.
  • We recommend that you use the __bl.session method to obtain the ID that corresponds to the reported content. The sid parameter specifies the ID. A PV corresponds to such an ID. If a PV is reported multiple times, the ID is the same.

[Back to the top]

event()

You can call the event() method to count the frequency, success rate, and duration of custom events or tasks in business scenarios.

Syntax of event():
__bl.event({key: 'xxx', success: xxx, time: xxx})
Table 7. Request parameters of event()
Parameter Type Description Required Default value
key String The name of the event. Yes N/A
success Boolean Specifies whether the event is successful. No true
time Number The duration of the event. Unit: ms. No 0
c1 String A custom supplementary field. No N/A
c2 String A custom supplementary field. No N/A
c3 String A custom supplementary field. No N/A
Example of event():
__bl.event({
  key: 'submit-xxx',
  success: false,
  time: 100
});

[Back to the top]

setConfig()

You can call the setConfig() method to modify specific configuration items after the SDK initialization. For more information, see SDK reference.

Syntax of setConfig():

__bl.setConfig(next)
Table 8. Request parameters of setConfig()
Parameter Type Description Required Default value
next Object The configuration item and its value that you want to modify. Yes N/A

Example of setConfig(): Change the value of the disableHook parameter to disable automatic API reporting.

__bl.setConfig({
    disableHook: true
});            

[Back to the top]

setPage()

You can call the setPage() method to reset the page name of a page. By default, PV data is reported again. This method is typically used for single-page applications (SPAs). For more information, see Page data reporting of SPAs.

Syntax of setPage():

__bl.setPage(page, sendPv)
Table 9. Request parameters of setPage()
Parameter Type Description Required Default value
page String The new page name. Yes N/A
sendPv Boolean Specifies whether to report PV data. By default, PV data is reported. No true
Example of setPage():
Set the name of the current page to the current URL hash, and report PV data again.
__bl.setPage(location.hash);

Set the name of the current page to homepage without triggering PV data reporting.
__bl.setPage('homepage', false);          

[Back to the top]

setCommonInfo()

You can call the setCommonInfo() method to set common fields.

Syntax of setCommonInfo():

__bl.setCommonInfo(obj)
An object is passed in the setCommonInfo() method. Example of setCommonInfo():
__bl.setCommonInfo({
  name: 'xxx',
  common: 'xxx'
});          
Note We recommend that you limit the size of the object for this method. Otherwise, the GET request is large in size and may fail.

[Back to the top]

custom()

You can call the custom() method to report custom business information.

Syntax of custom():

__bl.custom(obj, sampling)
Table 10. Request parameters of custom()
Parameter Type Description Required Default value
obj Object The business information. Yes ''
sampling Number The sample rate. No ''
Example of custom():
__bl.custom({
  key1: 'xxx', // The value must be a string that cannot exceed 20 characters in length.
  key2: 'xxx'
}, 10); // A value of 10 indicates that the sample rate is 1/10.    
Note We recommend that you limit the size of the object for this method. Otherwise, the GET request is large in size and may fail.

[Back to the top]

Create multiple instances

Use npm packages to create multiple instances. The official npm package alife-logger has been published.

Web page

  • Syntax:
    const BrowerLogger = require('alife-logger');
    const bl2 = BrowerLogger.createExtraInstance(props); // Create instances by using the createExtraInstance method.
    bl2.custom({
      key: 'biz',
      msg: 'msg info'
    });
    Note The props parameter is of the Object type. The parameters contained in the props parameter are basically the same as those in the SDK configurations.
  • The new instances report only custom information:
    var props = {
      pid: 'xxxx', // The ID of the site whose data the new instances need to report.
      region: 'cn',
      page: '',
      uid: ''
    }

Weex

  • Syntax:
    const WeexLogger = require('alife-logger/weex');
    const wl2 = WeexLogger.createExtraInstance(props); // Create instances by using the createExtraInstance method.
    wl2.custom({
      key: 'biz',
      msg: 'msg info'
    });
    Note The props parameter is of the Object type. The parameters contained in the props parameter are basically the same as those in the SDK configurations.
  • The new instances report only custom information:
    var props = {
      pid: 'xxxx', // The ID of the site whose data the new instances need to report.
      region: 'cn',
      sendRequest: function(data, imgUrl) {
        // Send the GET log scheme.
      },
      postRequest: function(data, imgUrl) {
        // Send the POST log scheme.
      }
    }

Mini program

Syntax:
import MiniProgramLogger from 'alife-logger/miniprogram'; // Specify the path based on the type of the mini program, such as the DingTalk or Alipay mini program.
const MiniInstance = MiniProgramLogger.createExtraInstance({
  pid: 'xxxinstance',
  uid: 'userxxx', // Specify the ID of the user. The ID is used to collect UV data.
  region: 'cn', // Specify the ID of the region where the application to which logs are to be reported is deployed. A value of cn indicates China, and a value of sg indicates Singapore. If you do not specify the region ID, the region is China.
  // Specify the remote procedure call (RPC) method based on your business to perform browser monitoring of mini programs.
  sendRequest: (url, resData) => {
    // The sending method.
  }
});