SDK reference

更新时间:
复制 MD 格式

Application Real-Time Monitoring Service (ARMS) Browser Monitoring provides a variety of SDK configuration items to suit a wide range of requirements. For example, you can use these configuration items to ignore URLs, API operations, or JavaScript (JS) errors, aggregate pages by removing non-key characters from URLs, and reduce reported data or workloads by using random sampling.

Methods in this topic

pid | uid | tag | page | setUsername | enableSPA | parseHash | disableHook | ignoreUrlCase | urlHelper | apiHelper | parseResponse | ignore | disabled | sample | pvSample | sendResource | useFmp | enableLinkTrace | release | environment | behavior | c1\c2\c3 | autoSendPerf

Use SDK configuration items

You can use SDK configuration items by using one of the following methods:

  • When you install a Browser Monitoring agent to a page, add parameters to config based on your requirements.

    For example, in the following sample code, aside from the default pid parameter, the enableSPA parameter for single page applications (SPAs) is added to config:

    <script>
    !(function(c,b,d,a){c[a]||(c[a]={});c[a].config={pid:"xxxxxx",enableSPA:true};
    with(b)with(body)with(insertBefore(createElement("script"),firstChild))setAttribute("crossorigin","",src=d)
    })(window,document,"https://sdk.rum.aliyuncs.com/v1/bl.js","__bl");
    </script>                    
  • After a page is initialized, call the setConfig method in the JavaScript code to modify the configuration items.

    The __bl.setConfig(next) method accepts the following parameter:

    Parameter

    Type

    Description

    Required

    Default value

    next

    Object

    The configuration item and its value that you want to modify.

    Yes

    None

pid

pid

String

The unique ID of the project. It is automatically generated by ARMS when it creates a site.

Yes

None

[Back to Top]

uid

uid

String

The ID of the user. The value is an identifier of the user and can be used to search for the user. You can specify a custom value. If you do not specify this parameter, the SDK is automatically generated and updated every six months.

  • Weex scenario: required

  • Other scenarios: not required

  • Weex Scenario: None

  • Other scenarios: automatically generated by the SDK

The following code provides an example on how to call the setConfig method to modify the SDK configuration item:

__bl.setConfig({
    uid: 12345
});        
Note

You cannot call the setConfig method to modify the uid parameter when you monitor mini programs. Instead, you can call the setUsername method to identify a user.

[Back to Top]

tag

tag

String

The input tag. Each log carries a tag.

No

None

[Back to Top]

page

page

String

The page name.

No

By default, the key part of the current page URL is taken: host + pathname.

Note

You can use the ignoreErrors property to query errors that you want to report. For more information, see ignore.

[Back to Top]

setUsername

setUsername

Function

Used to set a method that needs to return a user name of type String.

No

None

This configuration item is used to create a function. This function is used to obtain a username as a string. After the username is obtained, you can implement end-to-end session tracing and query sessions based on the username to troubleshoot issues.

Note
  • If the username cannot be obtained when the page is initialized, you can set the return value to null instead of a temporary username. If you set the return value to null, the setUsername method will be called again to obtain the username when the SDK is used to send logs. However, if you set the return value to a temporary username, the temporary username is used and setUsername is not called again to obtain the actual username.

  • The setUsername method can only be set once during runtime. To modify the method, restart the application.

The following code provides an example on how to call the setConfig method to modify the SDK configuration item:

__bl.setConfig({
    setUsername: function () {
        return "username_xxx";
    }
});            

[Back to Top]

enableSPA

enableSPA

Boolean

Listen to hashchange events on the page and report the PV again. This is applicable to single-page application scenarios.

No (supported only in Web scenarios)

false

[Back to Top]

parseHash

parseHash

Function

Used with enableSPA.

No

See below

In single-page application (SPA) scenarios (see SPA page data reporting), if enableSPA is set to true, the parseHash parameter parses the URL hash into the Page field when a hashchange event occurs.

Default value

The default value is obtained by using the following string processing method:

function (hash) {
    var page = hash ? hash.replace(/^#/, '').replace(/\?.*$/, '') : '';
    return page || '[index]';
}           

Typically, you do not need to modify this parameter. However, if you want to use a custom page name to report page-specific data, or if the URL hash is complex, you can modify this configuration item. Example:

// Define the mapping between URL hashes and page names.
var PAGE_MAP = {
    '/': 'homepage',
    '/contact': 'contact us',
    '/list': 'data list',
    // ...
};
// Call the SDK method after the page is loaded.
window.addEventListener('load', function (e) {
    // Call the setConfig method to modify the SDK configuration item.
    __bl.setConfig({
        parseHash: function (hash) {
            key = hash.replace(/\?.*$/, '');
            return PAGE_MAP[key] || 'unknown page';
        }
    });
});

[Back to Top]

disableHook

Important

The disableHook parameter takes effect only when the configurations are initialized.

disableHook

Boolean

Disable AJAX request listeners.

No

false: By default, it listens and is used to report the success rate of API calls.

[Back to Top]

ignoreUrlCase

ignoreUrlCase

Boolean

Ignore Page URL case.

No

true: Case insensitive by default.

[Back to Top]

urlHelper

urlHelper

*

Instead of the old parameter ignoreUrlPath, it is used to configure URL filtering rules.

No

See below

When a page URL is similar to http://example.com/projects/123456 (where the number after projects is the project ID), reporting example.com/projects/123456 as the page prevents pages from being clustered into a single category when you view the data. In this case, to ensure that similar pages are clustered, you can use the urlHelper parameter to filter out non-critical characters, such as the project ID in this example.

Important
  • The urlHelper parameter replaces the ignoreUrlPath parameter to ignore non-key characters in page URLs. If you specify the ignoreUrlPath parameter, the configuration still takes effect. If both the ignoreUrlPath and urlHelper parameters are specified, the configuration specified by the urlHelper parameter takes effect.

  • This setting applies only when the SDK automatically captures the page URL as the page value. The SDK ignores this setting if you manually set the page value by calling the setPage or setConfig methods (see SDK methods), or if enableSPA is set totrue.

Default value

The default value of this configuration item is the array in the following sample code. In most cases, you do not need to modify the value:

[
    // Replace all digits in the path with asterisks (*).
    {rule: /\/([a-z\-_]+)?\d{2,20}/g, target: '/$1**'},
    // Remove a trailing slash (/) from the URL.
    /\/$/
]                    

By default, this setting replaces numeric identifiers that follow a path segment. For example, bothxxxx/00001 andxxxx/00002 becomexxxx/**, just as an original URL likexxxx/123456 would.

Value types

The value of the urlHelper parameter can be of the following types:

  • String orRegExp (regular expression): Removes the matched part of the URL string.

  • Object<rule, target>: An object with rule and target keys. These are passed as arguments to the JavaScript String.prototype.replace() method. For details, see the String.prototype.replace() documentation.

  • Function: A function that accepts the original URL string as an argument. Its return value is used as the final page value.

  • Array: An array containing multiple rules, where each rule can be any of the types described above.

[Back to Top]

apiHelper

apiHelper

*

Instead of the old parameter ignoreApiPath, it is used to configure API filtering rules.

No

See below

This parameter is used to remove non-key characters in page URLs when page-specific data about API operations is automatically reported. The usage and function of this parameter are the same as those of urlHelper.

Important

The apiHelper parameter replaces the ignoreApiPath parameter to ignore non-key characters in URLs of API operations. If you specify the ignoreApiPath parameter, the configuration still takes effect. If both the ignoreApiPath and apiHelper parameters are specified, the configuration specified by the apiHelper parameter takes effect.

Default value

The default value of this parameter is an object and does not need to be modified:

{rule: /(\w+)\/\d{2,}/g, target: '$1'}                    

This default setting filters out trailing numbers in API URL paths, such as in xxxx/123456.

If you need to report parameters from the query string (the part of an API URL after the ?), such as the pid parameter in https://arms.console.aliyun.com/apm?pid=fr6fbgbeot, you must use manual reporting:

  • Call the ignore method to disable automatic data reporting. For more information, see ignore.

  • Call the api() method to manually report the page-specific data about API operations. For more information, see api().

[Back to Top]

parseResponse

parseResponse

Function

Used to parse the data returned during the automatic reporting API.

No

See below

This configuration item is used to parse the data returned when the page-specific data of API operations is automatically reported.

Default value

The following sample code shows the default configurations:

function (res) {
    if (!res || typeof res !== 'object') return {};
    var code = res.code;
    var msg = res.msg || res.message || res.subMsg || res.errorMsg || res.ret || res.errorResponse || '';
    if (typeof msg === 'object') {
        code = code || msg.code;
        msg = msg.msg || msg.message || msg.info || msg.ret || JSON.stringify(msg);
    }
    return {msg: msg, code: code, success: true};
}                    

The default function parses the response to extract the msg and code properties. While this function is suitable for most applications, you can override it if it does not meet your business requirements.

[Back to Top]

ignore

ignore

Object

Ignore the specified URL/API/JS error. Logs that meet the rules will be ignored and will not be reported. They include sub-configuration items ignoreUrls, ignoreApis, ignoreErrors, and ignoreResErrors.

No

See below

The value of the ignore parameter is an object that contains four properties: ignoreUrls, ignoreApis, ignoreErrors, and ignoreResErrors. You can set one or more properties of the parameter value.

Default value

The following sample code shows the default configurations:

ignore: {
        ignoreUrls: [],
        ignoreApis: [],
        ignoreErrors: [],
        ignoreResErrors: []
    },                    

ignoreUrls

The ignoreUrls property specifies URLs to ignore. Logs from URLs that match a specified pattern are not reported. The value can be a string, regular expression, function, or an array containing these types. Example:

__bl.setConfig({
                ignore: {
                    ignoreUrls: [
                    'http://host1/',  // string
                    /.+?host2.+/,     // regular expression
                    function(str) {   // function
                        if (str && str.indexOf('host3') >= 0) {
                            return true;   // Do not report
                        }
                        return false;      // Report
                    }]
                }
            });                    

ignoreApis

The ignoreApis property specifies APIs to ignore. Calls to APIs that match a specified pattern are not monitored. The value can be a string, regular expression, function, or an array containing these types. Example:

__bl.setConfig({
                ignore: {
                    ignoreApis: [
                    'api1','api2','api3', // string
                    /^random/,  // regular expression
                    function(str) { // function
                        if (str && str.indexOf('api3') >= 0) return true;   // Do not report
                        return false;   // Report
                    }]
                }
            });                    

ignoreErrors

The ignoreErrors property specifies JS errors to ignore. JS errors that match a specified pattern are not reported. The value can be a string, regular expression, function, or an array containing these types. Example:

__bl.setConfig({
                ignore: {
                    ignoreErrors: [
                    'test error', // string
                    /^Script error\.?$/, // regular expression
                    function(str) { // function
                        if (str && str.indexOf('Unknown error') >= 0) return true;   // Do not report
                        return false;   // Report
                    }]
                }
            });            

ignoreResErrors

The ignoreResErrors property specifies resource errors to ignore. Resource errors that match a specified pattern are not reported. The value can be a string, regular expression, function, or an array containing these types. Example:

__bl.setConfig({
                ignore: {
                    ignoreResErrors: [
                    'http://xx/picture.jpg', // string
                    /jpg$/, // regular expression
                    function(str) { // function
                        if (str && str.indexOf('xx.jpg') >= 0) return true;   // Do not report
                        return false;   // Report
                    }]
                }
            });

[Back to Top]

disabled

disabled

Boolean

Specifies whether to disable the log reporting function.

No

false

[Back to Top]

sample

sample

Integer

Sets the API log sampling configuration. The value must be an integer from 1 to 100. It samples performance logs and successful API logs at a rate of 1/sample. For more information about related metrics, see Statistical metrics.

No

1

Benefits:

  • Reduces costs by reporting only sampled API data. We recommend that you identify the data that does not require monitoring by setting the ignore parameter. For more information, see ignore.

  • Reduces the performance overhead of data collection.

Description:

  • You can set this configuration item to randomly select and report performance logs and logs about successful API operations. This reduces the volume of reported data and the workloads. When ARMS processes the reported logs in the background, ARMS restores the data based on the sampling configurations. In this way, metrics such as the JS error rate or API failure rate are not affected by sampling and remain accurate. However, when you set this parameter, you may be unable to obtain the detailed data such as the API details.

  • The default value of sample is 1. Valid values are integers from 1 to 100. The sampling rate is 1/sample. For example, 1 means 100% sampling, 10 means 10% sampling, and 100 means 1% sampling.

Warning

When the total data volume is small and random sampling is still performed, a large deviation may be introduced to the statistical result. We recommend that you use this configuration item for the websites whose daily average page views (PVs) is more than 1 million.

[Back to Top]

pvSample

Parameter

Type

Description

Required

Default value

pvSample

Integer

Sets the sampling configuration for PV logs. The value is an integer from 1 to 100, where the sampling rate is 1/pvSample.

No

1

Benefits:

  • Reduces costs by reporting only sampled PV data.

  • Reduces the performance overhead of data collection.

Description:

  • You can set this configuration item to randomly select and report PV logs. This reduces the volume of reported data and the workloads. When ARMS processes the reported logs in the background, ARMS restores the data based on the sampling configurations. In this way, metrics such as the JS error rate are not affected by sampling and remain accurate.

  • The default value of pvSample is 1. The sampling rate is 1/pvSample. For example, a value of 1 means 100% sampling, 10 means 10% sampling, and 100 means 1% sampling.

[Back to Top]

sendResource

sendResource

Boolean

Reports static resources on the page.

No

false

If the sendResource parameter is set to true, the static resources on the page are reported when the page's load event triggers. If a page loads slowly, you can view its static resource waterfall chart on the Session Traces page to find the cause.

The following code provides an example on how to set the sendResource parameter:

<script>
!(function(c,b,d,a){c[a]||(c[a]={});c[a].config={pid:"xxxxxx",sendResource:true};
with(b)with(body)with(insertBefore(createElement("script"),firstChild))setAttribute("crossorigin","",src=d)
})(window,document,"https://sdk.rum.aliyuncs.com/v1/bl.js","__bl");
</script>            
Note

When you want to troubleshoot slow page loading, you must configure the sendResource parameter in config, as shown in the preceding sample code. This way, the static resources are reported when the load event is triggered. If you call the setConfig method, the static resources may be reported after the load event is complete. In this case, the sendResource parameter cannot help you identify the cause of slow page loading.

[Back to Top]

useFmp

useFmp

Boolean

Collects first-screen FMP(First Meaningful Paint, first valid rendering) data.

No

false

[Back to Top]

enableLinkTrace

enableLinkTrace

Boolean

For more information about back-to-back Tracing Analysis, see Diagnose API errors with front-to-back tracing.

No (only supported by Web scenarios, Alipay applets, WeChat applets, and DingTalk applets)

false

[Back to Top]

release

Important

You must configure release in config during page initialization. Do not call the setConfig method.

release

String

The version of the application. We recommend that you configure this parameter to view the report information of different versions.

No

undefined

[Back to Top]

environment

environment

String

The environment field. Valid values: prod, gray, pre, daily, and local.

  • The value prod indicates an online environment.

  • The value gray indicates a phased-release environment.

  • The value pre indicates a staging environment.

  • The value daily indicates a daily environment.

  • The value local indicates a local environment.

No

prod

[Back to Top]

behavior

behavior

Boolean

Specifies whether to record the user behavior that reports errors for easy troubleshooting.

No (supported only in Web and mini-program scenarios)

The default value of Browser is true, and the default value of mini program is false.

[Back to Top]

autoSendPerf

autoSendPerf

Boolean

Specifies whether to allow automatic sending of performance logs.

No

true

[Back to Top]

c1\c2\c3

In addition to the preceding configuration items, the ARMS SDK provides three custom configuration items that you can configure fields to meet your business requirements. After you configure the fields, the fields values are included in all reported logs.

c1

String

Custom service field. Each log carries the field.

No

None

c2

String

Custom service field. Each log carries the field.

No

None

c3

String

Custom service field. Each log carries the field.

No

None

Note

c1\c2\c3 is the data that is carried in all reports on the current custom page. Generally, c1\c2\c3 is related to your services. When you initialize Browser Monitoring SDK for JavaScript, you can specify SDK parameters to query data, such as the VIP level of a user.

[Back to Top]