SDK methods

更新时间:
复制 MD 格式

Browser Monitoring SDKs provide methods to report data and modify SDK configurations.

Methods in this topic

api()

Use api() to report the success rate of API calls on a page.

By default, the SDK monitors AJAX requests on the page and calls this API to report data. If your page requests data using JSONP or other custom methods, such as a client SDK, call the api() method to report the data manually.

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. Parameters for api()

Parameter

Type

Description

Required

Default value

api

String

The name of the method.

Yes

None

success

Boolean

Specifies whether the call is successful.

Yes

None

time

Number

The amount of time consumed by the call.

Yes

None

code

String/Number

The status code.

No

None

msg

String

The response information.

No

None

begin

Number

The time when the API call started. The value is a timestamp.

No

None

traceId

String

The value of EagleEye-TraceID.

No

None

sid

String

The value of EagleEye-SessionID.

No

None

api() example:

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

[Back to Top]

error()

Call the error() method to report JS errors or exceptions on monitored pages. You can view the details on the JS Error Diagnostics page of Browser Monitoring.

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

error() syntax:

__bl.error(error, pos)

Table 2. Parameters for error()

Parameter

Type

Description

Required

Default value

error

Error

The JS error object.

Yes

None

pos

Object

The location where the error occurs. The location contains the following attributes: pos.filename, pos.lineno, and pos.colno.

No

None

pos.filename

String

The name of the file where the error occurs.

No

None

pos.lineno

Number

The number of the line where the error occurs.

No

None

pos.colno

Number

The number of the column where the error occurs.

No

None

Example 1: Listen for and report error events.

window.addEventListener('error', function (ex) {
    // The event argument usually contains location information.
    window.__bl && __bl.error(ex.error, ex);
});            

error() example 2: Report a custom error message.

window.__bl && __bl.error(new Error('A custom error occurred'), {
    filename: 'app.js', 
    lineno: 10, 
    colno: 15
});            

error() Example 3: Report an error message of a custom type.

__bl.error({name:'CustomErrorLog',message:'this is an error'}, {
    filename: 'app.js', 
    lineno: 10, 
    colno: 15
});           

[Back to Top]

sum()

Use the sum() method to report custom statistics. This method is typically used to count the occurrences of a business event. You can view data reported by the sum() method on the Custom Statistics page:

Note

After you report data, it is displayed on the Custom Statistics page a few minutes later.

  • 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. sum() parameters

Parameter

Type

Description

Required

Default value

key

String

The name of the event.

Yes

None

value

Number

The number of reported items at a time.

No

1

sum() example:

__bl.sum('event-a');
__bl.sum('event-b', 3);

[Back to Top]

avg()

Use the avg() method to report custom data. This method is typically used to calculate the average number of occurrences or value of a specific business event. You can view the data reported by avg() 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. avg() parameters

Parameter

Type

Description

Required

Default value

key

String

The name of the event.

Yes

None

value

Number

The number of reported items.

No

0

Example of avg():

__bl.avg('event-a', 1);
__bl.avg('event-b', 3);

[Back to Top]

reportBehavior()

Call reportBehavior() to immediately report the current behavior queue.

If you do not manually call this method, when a JS error occurs, the current behavior queue is automatically reported. The maximum size of a queue is 100. If the queue contains more than 100 behavior records, behavior records are discarded from the header of the queue.

Note

To call this method, you must set the behavior parameter to true in the SDK configurations.

reportBehavior() syntax:

__bl.reportBehavior()

reportBehavior() parameters: None.

[Back to Top]

performance()

Important

This method is applicable only to web clients.

Call the performance() method after the window.onload event to report custom performance metrics.

Note

You can call this method only after the onLoad method is called. Otherwise, the call fails because the collection of default performance metrics is incomplete. The performance() method can be called only once during each PV.

To use the performance() method:

  1. Set the autoSendPerf parameter to false to disable automatic reporting of performance metrics and wait for manual reporting.

  2. Call the __bl.performance(Object) method to manually report custom metrics. This call sends both your custom metrics and the default performance metrics collected by the SDK.

Example 1: Using performance() with a CDN

window.onload = () => {
 setTimeout(()=>{
  __bl.performance({cfpt:100, ctti:200, t1:300, …});
 }, 1000); // Delay to ensure all default performance metrics are collected before manual reporting.
};

Example 2: Using performance() with an npm package

const BrowserLogger = require('@arms/js-sdk');
const __bl = BrowserLogger.singleton({pid:'Your unique site ID'});
window.onload = () => {
 setTimeout(()=>{
  __bl.performance({cfpt:100, ctti:200, t1:300, …});
 }, 1000);// Delay to ensure all default performance metrics are collected before manual reporting.
};
Note

Descriptions of custom performance metrics:

  • cfpt: the custom first paint time

  • ctti: the first custom time to interact

  • t1 to t10: 10 custom performance metrics

[Back to Top]

setConfig()

Call setConfig() after SDK initialization to modify specific configuration items. For more information, see SDK reference.

Syntax of setConfig():

__bl.setConfig(next)

Table 8. Parameters for setConfig()

Parameter

Type

Description

Required

Default value

next

Object

The parameter that you want to modify and the new parameter value.

Yes

None

[Back to Top]

setPage()

Use setPage() to reset the page name, which by default triggers a new PV report. This method is typically used for a single-page application (SPA). For more information, see Page data reporting of SPAs.

Note

When the PV data is reported again, existing data is not overwritten. A new data entry is added.

Syntax of setPage():

__bl.setPage(page, sendPv)

Table 9. setPage() parameters

Parameter

Type

Description

Required

Default value

page

String

The new page name.

Yes

None

sendPv

Boolean

Specifies whether to report PV data. By default, PV data is reported.

No

true

Example of setPage():

// Set the page name to the current URL hash and report a new PV.
__bl.setPage(location.hash);

// Set the page name to 'homepage' without reporting a new PV.
__bl.setPage('homepage', false);          

[Back to Top]

setCommonInfo()

Use setCommonInfo() to set common fields.

setCommonInfo() syntax:

__bl.setCommonInfo(obj)

The setCommonInfo() method accepts an object parameter:

__bl.setCommonInfo({
  name: 'xxx',
  common: 'xxx'
});          
Note

Limit the object size. A large object can result in a long GET request, which might fail.

[Back to Top]

addBehavior()

Call the addBehavior() method to append a custom user behavior to the current behavior queue.

The SDK maintains a user behavior queue with a maximum length of 100 entries. You can call the addBehavior() method to append a custom user behavior to the queue. When a JS error occurs, the SDK reports the current behavior queue and clears it.

You can view the user behavior traceback on the JS Error Diagnostics page. For instructions, see Use user behavior traceback to diagnose JS errors.

Note

To call this method, you must set the behavior parameter to true in the SDK configurations.

The syntax for addBehavior() is as follows:

__bl.addBehavior(behavior)

Table 10. addBehavior() parameters

Parameter

Type

Description

Required

Default value

data

Object

The behavior data. This parameter has the following two required fields:

  • name: the behavior name of the STRING type. The name can be up to 20 characters in length.

  • message: the behavior content of the STRING type. The value can be up to 200 characters in length.

Yes

None

page

String

The page where the behavior happens.

No

Value of the location.pathname parameter

The following example shows how to use addBehavior():

_bl.addBehavior({
  data:{name:'string',message:'string'},
  page:'string'
})

[Back to Top]

Create multiple instances

To create multiple instances, use the @arms/js-sdk npm package.

Web pages

  • Example:

    const BrowerLogger = require('@arms/js-sdk');
    const bl2 = BrowerLogger.createExtraInstance(props); // Create an instance 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 site ID where the new instance reports data.
      region: 'cn',
      page: '',
      uid: ''
    }

Weex pages

  • Example:

    const WeexLogger = require('@arms/js-sdk/weex');
    const wl2 = WeexLogger.createExtraInstance(props); // Create an instance 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 site ID where the new instance reports data.
      region: 'cn',
      sendRequest: function(data, imgUrl) {
        // The method for sending logs using GET requests.
      },
      postRequest: function(data, imgUrl) {
        // The method for sending logs using POST requests.
      }
    }

Mini programs

Example:

import MiniProgramLogger from '@arms/js-sdk/miniapp'; // Select the path for your mini program type (e.g., DingTalk, Alipay).
const MiniInstance = MiniProgramLogger.createExtraInstance({
  pid: 'xxxinstance',
  uid: 'userxxx', // User ID for collecting UV data.
  region: 'cn', // The region where logs are reported. Set the value to `cn` for China or `sg` for Singapore. Defaults to `cn` if unspecified.
  // For basic mini program monitoring, you must manually pass the remote procedure call (RPC) method. Implement the method based on your business requirements.
  sendRequest: (url, resData) => {
    // The method for sending data.
  }
});