Monitor other types of mini programs

更新时间:
复制 MD 格式

This topic describes how to use ARMS browser monitoring to monitor standard-compliant mini programs other than those for DingTalk, Alipay, and WeChat. It also covers common configurations, API methods, and advanced scenarios.

Basic usage

The basic setup involves three steps: installing and initializing the npm package, reporting logs, and configuring security domain names.

  1. Install and initialize the npm package.

    1. In your mini program project, install the@arms/js-sdk npm package to enable monitoring.

      npm install @arms/js-sdk
    2. Add the following code to a monitor.js file in your /utils directory to initialize the SDK.

      Note

      You can customize the name and location of the JavaScript (JS) file.

      import MiniProgramLogger from '@arms/js-sdk/miniapp';
      const Monitor = MiniProgramLogger.init({
          pid: 'xxx',
          uid: 'userxxx', // Set the user ID, which is used for UV statistics.
          region: 'cn', // Specify the region where the application is deployed. Set this parameter to 'cn' for the Chinese mainland or 'sg' for regions outside the Chinese mainland. The default value is 'cn'.
          // For basic mini program monitoring, you must manually provide the RPC function. 
          // Implement the function based on your business logic. The following example shows how to make a call in a DingTalk E-App.
          sendRequest: (url, resData) => {
                // You must configure this part. It supports both GET and POST reporting.
              // Demo in DingTalk
              var method = 'GET';
              var data;
              if (resData) {
                  method = 'POST';
                  data = JSON.stringify(resData);
              }
              dd.httpRequest({
                  url: url,
                  method: method,
                  data: data,
                  fail: function (error) {
                      //...
                  }
              });
          },
           // Manually provide a function to get the current page path. 
           // Implement the function based on your business logic. The following example shows how to make a call in a DingTalk E-App.
           getCurrentPage: () => {
                // You must configure this part.
              if (typeof getCurrentPages !== 'undefined' && typeof getCurrentPages === 'function') {
                  var pages = (getCurrentPages() || []);
                  var pageLength = pages.length;
                  var currPage = pages[pageLength - 1];
                  return (currPage && currPage.route) || null;
              }
           }
      });
      
      export default Monitor;
      Note

      For more information about the parameters, see SDK parameters.

  2. Report logs.

    1. In app.js, use one of the following methods to report logs:

      • Use the Monitor.hookApp(options) method to automatically capture Error logs. The options parameter is the original configuration object of your App.

        import Monitor from '/utils/monitor';
        
            App(Monitor.hookApp({
              onError(err) {
                console.log('Entering onError:', err);
              },
              onLaunch() {
                console.log('Entering onLaunch');
              },
        
              onShow(options) {
              },
              onHide() {
              }
            }));                
      • Use the Monitor.error(err) method to manually report Error logs.

        import Monitor from '/utils/monitor';
        
            App({
              onError(err) {
                  Monitor.error(err);
                console.log('Entering onError:', err);
              },
              onLaunch() {
                console.log('Entering onLaunch');
              },
        
              onShow(options) {
              },
              onHide() {
              }
            });
    2. In the JS file for a page, use one of the following methods to report logs:

      • Use the Monitor.hookPage(options) method to automatically report page view (PV) and health data.

        Note

        This method does not automatically report API requests.

        import Monitor from '/utils/monitor';
        
            Page(Monitor.hookPage({
               data: {},
                onLoad(query) {
                },
                onReady() {
                    // The page has finished loading.
                },
                onShow() {
        
                },
                onLoad(query) {
        
                },
                onHide() {
        
                },
                onUnload() {
        
                },
                onTitleClick() {
                    /**
                     * Report custom instrumentation data.
                     * @desc
                     */
                    Monitor.sum('titleClick');
                }       
            }));
      • Call API methods to manually report data.

        Note

        For more information about API methods, see API methods.

        import Monitor from './util/monitor';
        
            Page({
               data: {},
                onShow() {
                    Monitor.pageShow();
                },
                onHide() {
                    Monitor.pageHide();
                },
                onUnload() {
                    Monitor.pageHide();
                },
                onTitleClick() {
                    /**
                     * Report custom instrumentation data.
                     * @desc
                     */
                    Monitor.sum('titleClick');
                }       
            });
  3. Configure security domain names.

    • If you set region to cn, add https://arms-retcode.aliyuncs.com to your list of valid domain names.

    • If you set region to sg, add https://arms-retcode-sg.aliyuncs.com to your list of valid domain names.

API methods

Method

Parameter

Description

hookApp

{}

Wraps the original App configuration object to automatically instrument App lifecycle callbacks.

hookPage

{}

Wraps the original Page configuration object to automatically instrument Page lifecycle callbacks.

setCommonInfo

{[key: string]: string;}

Sets common fields that are added to all reported data. This is useful for scenarios like phased releases.

setConfig

{[key: string]: string;}

Sets configuration fields. For more information, see the Browser Monitoring SDK configuration.

pageShow

{}

Reports a page show event to send page view (PV) data.

pageHide

{}

Reports a page hide event to send health data.

error

String/Object

Reports an error log.

api

See Frontend API reference.

Reports API request logs.

sum/avg

String

Reports custom metrics for sum and average calculations.

Note

To use hookApp and hookPage for automatic lifecycle instrumentation, your mini program must follow the standard mini program specifications. This means the App level must have an onError method, and the Page level must have onShow, onHide, and onUnload methods. For an example, see Basic usage.

Most log reporting APIs are consistent with the web browser monitoring SDK. The usage of other APIs is described below:

  • To send PV data for the current page, call the pageShow() method within the Page's onShow lifecycle method.

    Note

    Do not use this method together with the hookPage() method. Otherwise, duplicate PV logs are reported.

    import Monitor from '/util/monitor';
    Page({
        onShow: function() {
            Monitor.pageShow();
        }
    })
  • To send health data for the current page and measure the health level and time on page, call the pageHide() method within the Page's onHide and onUnload lifecycle methods.

    Note

    Do not use this method together with the hookPage() method. Otherwise, duplicate logs are reported.

    import Monitor from '/util/monitor';
      Page({
    
          onHide: function() {
              Monitor.pageHide();
          },
          onUnload: function() {
              Monitor.pageHide();
          }
          ... 
      })

Advanced scenarios

If the basic usage does not meet your requirements, consider the advanced scenarios in this section.

  • Setting the uid (for UV statistics)

    • If the user ID is available before the SDK is initialized, you can set the uid directly in the init configuration.

    • If the user ID is not available at initialization, you can retrieve it before the application's onShow event and then set the uid by calling setCommonInfo({uid: 'xxx'}).

  • Setting common information for the mini program

    Use the setCommonInfo method to set common information for the mini program. ARMS browser monitoring analyzes the following fields:

    • sr: screen resolution

    • vp: viewport

    • dpr: device pixel ratio

    • ul: document language

    • dr: document referrer

    • ct: network connection type (for example, Wi-Fi or 3G)

      Warning

      Do not set too many fields by using the setCommonInfo method. Exceeding the request length limit may cause the request to fail.

SDK parameters

ARMS browser monitoring provides SDK parameters for advanced configuration. The following table describes common parameters applicable to this scenario.

Parameter

Type

Description

Required

Default

pid

String

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

Yes

None

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.

No

Automatically generated by the SDK

tag

String

The input tag. Each log carries a tag.

No

None

release

String

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

No

undefined

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

sample

Integer

The log sampling configuration. The value is an integer from 1 to 100. The performance logs and success API logs are sampled at the 1/sample ratio. For more information about the metrics of performance logs and success API logs, see Statistical metrics.

No

1

behavior

Boolean

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

No

false

For a complete list of SDK parameters, see the Browser Monitoring SDK configuration.