The Alibaba Cloud Browser Monitoring SDK provides methods for data reporting and methods for SDK configuration modification. This topic also describes how to create multiple SDK instances.
Methods in this topic
Data reporting APIs: api() | error() | sum() | avg() | reportBehavior() | performance()
Method APIs: setConfig() | setPage() | setCommonInfo() | addBehavior()
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.
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})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 return code. | No | None |
msg | String | The response information. | No | None |
begin | Number | The time when the request is initiated. 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 |
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: 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...
});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.
Syntax of error():
__bl.error(error, pos)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 of error(): Listen for and report JS errors on the page.
window.addEventListener('error', function (ex) {
// The event argument usually contains location information.
window.__bl && __bl.error(ex.error, ex);
});Example 2 of error(): Report a custom error message.
window.__bl && __bl.error(new Error('A custom error occurred'), {
filename: 'app.js',
lineno: 10,
colno: 15
});Example 3 of error(): Report an error message of a custom type.
__bl.error({name:'CustomErrorLog',message:'this is an error'}, {
filename: 'app.js',
lineno: 10,
colno: 15
});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:
Trend chart of custom events
Page views (PVs) and unique visitors (UVs) of an event
Dimension distribution information
After you report data, it appears on the Custom Statistics page a few minutes later.
Syntax of sum():
__bl.sum(key, value)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 |
Example of sum():
__bl.sum('event-a');
__bl.sum('event-b', 3);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)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);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.
To call this method, you must set the behavior parameter to true in the SDK configurations.
Syntax of reportBehavior():
__bl.reportBehavior()The reportBehavior() method does not accept any parameters.
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.
To call this method, you must set the behavior parameter to true in the SDK configurations.
Syntax of addBehavior():
__bl.addBehavior(behavior)Parameter | Type | Description | Required | Default value |
data | Object | The behavior data. This parameter has the following two required fields:
| Yes | None |
page | String | The page where the behavior happens. | No | Value of the location.pathname parameter |
Example of addBehavior():
__bl.addBehavior({
data:{name:'string',message:'string'},
page:'string'
})performance()
This method is applicable only to web clients.
Call the performance() method after the page onLoad event to report custom performance metrics in addition to the default performance metrics.
You can call this method only after the onLoad event occurs. 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, perform the following steps:
Set the autoSendPerf parameter to false to disable automatic reporting of performance metrics and wait for manual reporting.
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 of 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 of 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.
};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
setConfig()
Call setConfig() after SDK initialization to modify specific configuration items. For more information, see SDK reference.
Syntax of setConfig():
__bl.setConfig(next)Parameter | Type | Description | Required | Default value |
next | Object | The parameter that you want to modify and the new parameter value. | Yes | None |
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.
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)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);setCommonInfo()
Use setCommonInfo() to set common fields.
Syntax of setCommonInfo():
__bl.setCommonInfo(obj)The setCommonInfo() method accepts an object parameter:
__bl.setCommonInfo({
name: 'xxx',
common: 'xxx'
});Limit the object size. A large object can result in a long GET request, which might fail.
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' });NoteThe 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' });NoteThe 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: Select the import path that matches your mini program type, such as a DingTalk mini program or an Alipay mini program. The region parameter specifies where logs are reported: set it to cn to report logs to servers in China, or to sg to report logs to servers in Singapore. If you do not specify this parameter, logs are reported to servers in China.
import MiniProgramLogger from '@arms/js-sdk/miniapp'; // Select the path that matches your mini program type, such as a DingTalk mini program or an Alipay mini program.
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.
}
});