Real User Monitoring (RUM) provides comprehensive monitoring for mobile applications. You can use RUM to monitor and analyze key metrics in real time, such as application performance, crashes, and stuttering. This topic describes how to integrate the HarmonyOS software development kit (SDK) with your application.
Version requirements
The compatibleSdkVersion of the Stage application must be 5.0.0 (12) or later.
The SDK integration parameters changed in version 2.0.0 and are not compatible with earlier versions. When you upgrade to version 2.0.0 or later, you must follow the latest integration document to upgrade the SDK. This ensures that the SDK initializes correctly.
Step 1: Integrate the SDK
The HarmonyOS RUM SDK is published to a third-party repository. Add the SDK HAR package dependency to the `dependencies` section of the `oh-package.json5` file in your project. The configuration is as follows:
"dependencies": { "@alibabacloud_rum/harmony_sdk": "2.0.2" }After you configure the dependency, run the `ohpm install` command to install the package. The package is installed in the `oh_modules` directory of the project.
ohpm clean ohpm installRebuild the project to ensure that the configuration takes effect.
Step 3: Configure the SDK
1. Configure permissions
Check the `module.json5` configuration file of your application to ensure that the following permissions are included:
ohos.permission.INTERNET // Sends network data
ohos.permission.GET_NETWORK_INFO // Obtains network status information2. Configure ohmurl rules
Set `useNormalizedOHMUrl` to `true` in the project-level or module-level `build-profile.json5` file. If this configuration item does not exist, add it manually.
{
"app" : {
"products": [{
"buildOption": {
"strictMode": {
"useNormalizedOHMUrl": true
}
}
}]
}
}3. Configure the hvigor plugin
The Hvigor plugin works with the SDK to inject probe code into your HarmonyOS application at compile-time.
This plugin is used for network data collection. It currently supports the following network frameworks:
hms.collaboration.rcp
ohos.net.http
ohos.net.webSocket
ohos.net.socket.TCPSocket
If your project does not use these network libraries, you do not need to install the plugin.
Add the dependency declaration.
Add the plugin dependency to the `hvigor/hvigor-config.json5` file in your project:
{ "dependencies": { "@arms/rum-harmonyos-plugin": "^1.0.3" } }Install the dependency.
Method 1: Click Sync Now in the upper-right corner of the editor, or choose from the menu. DevEco Studio automatically installs the dependency based on the configuration in `hvigor-config.json5`.
Method 2: Run any command using the `hvigorw` command line interface (CLI). The CLI automatically installs the build dependency.
hvigorw --sync
(Required) Create a configuration file.
Create a configuration file named
alibabaCloudRumConfig.txtin the root directory of your project. This file specifies the scope of the source code for the plugin to process and ignore. The file must contain the following configurations:-hook: Specifies the directories or files to process. The plugin scans and processes the source files in these paths.-keep: Specifies the directories or files to exclude from processing. Paths specified by `keep` are skipped, even if they are included in a `hook` path.Network data collection is effective only for the paths configured in `hook`.
Example:
# Specify the root directory of the ets source code to process. -hook ./src/main/ets/ # Specify not to process any files in the hook directory. -keep ./src/main/ets/hook/Add the plugin to your module's build configuration file, `hvigorfile.ts`.
import { hapTasks } from '@ohos/hvigor-ohos-plugin'; // Import the plugin. import { AlibabaCloudRumPlugin } from '@arms/rum-harmonyos-plugin'; // In your build configuration export default { system: hapTasks, plugins: [ // Add the plugin instance. Note that you must call the function here. AlibabaCloudRumPlugin() ] };
4. Initialize the SDK
Method 1 (Recommended)
In the `onCreate` function of the custom AbilityStage in the entry module, add the following code.
AlibabaCloudRum.withServiceId("${your_serviceId}") // Obtain the ServiceId when you create the RUM application. .withEndpoint("${your_endpoint}") // Obtain the Endpoint when you create the RUM application. .withWorkspace("${your_workspace}")// Obtain the Workspace when you create the RUM application. .start(this.context.getApplicationContext()); // Get the application context.Method 2
If your application's business logic prevents SDK initialization in the `onCreate` lifecycle of the custom AbilityStage, you can initialize the SDK during the first page load lifecycle. In this case, the SDK will not collect application behaviors that occur before the first page loads. During the first page load lifecycle, add the following code:
AlibabaCloudRum.withServiceId("${your_serviceId}") // Obtain the ServiceId when you create the RUM application. .withEndpoint("${your_endpoint}") // Obtain the Endpoint when you create the RUM application. .withWorkspace("${your_workspace}")// Obtain the Workspace when you create the RUM application. .withUiContext(this.getUIContext()) // Get the uiContext. .start(getContext(this).getApplicationContext()) // Get the application context.
5. Data collection
The HarmonyOS SDK supports automatic data collection for some data types. For third-party network libraries, such as axios and webview, you must manually add instrumentation. The steps are as follows:
Axios network data collection
(Optional) To enable end-to-end distributed tracing, you must insert Alibaba Cloud's custom business request headers into the request. If you do not need distributed tracing, you can skip this step. Note that if you use end-to-end distributed tracing, you must first configure a host whitelist in the console. For more information, see Associate frontend and backend traces in Application Monitoring.
ImportantYou must obtain and assign a new custom header for each network request. Do not reuse the API call results for different request URLs.
function getInsertHeaderMap(requestUrl: string): Map<string, string> | undefinedParameter
Required
Description
Parameter constraints
Result if failed
requestUrl
Required
Request URL
String. A valid request URL.
The retrieval failed.
// The example shows how to insert a request header using `AxiosRequestConfig`. You can also implement a request interceptor to process `InternalAxiosRequestConfig.headers` to insert the header. import axios, { AxiosError, AxiosHeaders, AxiosResponse, AxiosRequestConfig, InternalAxiosRequestConfig } from '@ohos/axios' import { AlibabaCloudRumTrace } from '@alibabacloud_rum/harmony_sdk' let customHeaders: AxiosHeaders = new AxiosHeaders() let traceHeader = AlibabaCloudRumTrace.axios.getInsertHeaderMap("https://www.example.com"); if (traceHeader) { traceHeader.forEach((value: string, key: string) => { customHeaders.set(key, value); }) } // Insert into the actual request header using AxiosRequestConfig. let requestConfig: AxiosRequestConfig = { method: this.currMethod, headers: customHeaders, params: this.currRequestParam } axios.get("https://www.example.com", requestConfig);(Required) Collect data for normal and abnormal network requests.
function handleSuccess(requestUrl: string, method: string, responseCode: number, requestDataSizeByte?: number, downloadSizeByte?: number, timingParam?: object, remoteAddressIP?: string, requestHeader?: Record<string, Object>, responseHeader?: Record<string, Object>, resourceType?: string, requestBody?: string)Metric description:
Parameter
Required
Description
Parameter constraints
Result if failed
requestUrl
Required
Request URL
String. A valid request URL.
The network event is not collected.
method
Required
Request method
String. For non-HTTP request methods, pass an empty string.
The network event is not collected.
responseCode
Required
Response code
Number.
The network event is not collected.
requestDataSizeByte
Optional
Size of the uploaded request data
Number. Unit: bytes.
The network event is not collected.
downloadSizeByte
Optional
Download size
Number. Unit: bytes.
The network event is not collected.
timingParam
Optional
Time spent in each phase of the axios request
http.PerformanceTiming
The network event is not collected.
remoteAddressIP
Optional
Destination IP address
String
The related field is missing for the network event.
requestHeader
Optional
Request header. This parameter is required to use the distributed tracing feature.
Record type
The related field is missing for the network event.
responseHeader
Optional
Response header
Record type
The related field is missing for the network event.
resourceType
Optional
Resource type
String. Follows the Content-Type field of Multipurpose Internet Mail Extensions (MIME) types.
The related field is missing for the network event.
requestBody
Optional
Request content
String data type
The related field is missing for the network event.
Collect data for abnormal network requests:
function handleError(requestUrl: string, method: string, requestDataSizeByte: number, errorParam: Error,requestHeader?: Record<string, Object>)Parameter
Required
Description
Parameter constraints
Result if failed
requestUrl
Required
Request URL
String. A valid request URL.
The network event is not collected.
method
Required
Request method
String. For non-HTTP request methods, pass an empty string.
The network event is not collected.
requestDataSizeByte
Required
Size of the uploaded request data
Number. Unit: bytes.
The network event is not collected.
errorParam
Required
Network error
Business error type
The network event is not collected.
requestHeader
Optional
Request header
Record type
The related field is missing for the network event.
The following is an example:
axios.get("http://www.example.com",requestConfig).then((responseData: AxiosResponse) => { AlibabaCloudRumTrace.axios.handleSuccess("http://www.example.com", "GET", responseData.status, requestDataSize, downloadSize, responseData.performanceTiming); }).catch((err: BusinessError) => { AlibabaCloudRumTrace.axios.handleError("http://www.example.com", "GET", 0, err); });
Webview data collection
Add the SDK collection logic to the lifecycle callbacks of the Web component. The steps are as follows:
Insert the JS script:
In the parameters of
javaScriptOnDocumentStart, addAlibabaCloudRumTrace.Web.getScriptItem().Add instrumentation in the `onPageEnd` lifecycle:
In
onPageEnd, addAlibabaCloudRumTrace.Web.onPageEndHilt(this.controller).Destroy the SDK collection resources when the component is uninstalled:
In
onDisAppear, addAlibabaCloudRumTrace.Web.onDisAppearHilt(this.controller).
Code example:
import { AlibabaCloudRumTrace } from '@alibabacloud_rum/harmony_sdk';
Web()
.javaScriptOnDocumentStart([AlibabaCloudRumTrace.Web.getScriptItem()])
.onPageEnd(() => {
AlibabaCloudRumTrace.Web.onPageEndHilt(this.controller);
// this.controller: Must be the WebviewController bound to the current Web component.
})
.onDisAppear(() => {
AlibabaCloudRumTrace.Web.onDisAppearHilt(this.controller);
// this.controller: Must be the WebviewController bound to the current Web component.
})