Real User Monitoring (RUM) provides comprehensive mobile application monitoring, including real-time analysis of performance, crashes, and stuttering. This guide walks you through integrating the HarmonyOS 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, follow the latest integration guide to ensure 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:
"dependencies": { "@alibabacloud_rum/harmony_sdk": "2.0.2" }After you configure the dependency, run `ohpm install` to install the package. The package is installed in the `oh_modules` directory.
ohpm clean ohpm install -
Rebuild the project to ensure that the configuration takes effect.
Step 3: Configure the SDK
1. Configure permissions
Verify that the `module.json5` configuration file of your application includes the following permissions:
ohos.permission.INTERNET // Sends network data
ohos.permission.GET_NETWORK_INFO // Obtains network status information
2. 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 defines which source code paths the plugin processes or ignores. Include the following configurations:-hook: Directories or files to process. The plugin scans the source files in these paths.-keep: Directories or files to exclude. Paths specified by `keep` are skipped even if they fall within 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 instead. In this case, the SDK does not collect application behaviors that occur before the first page loads. Add the following code during the first page load lifecycle:
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 automatically collects some data types. For third-party network libraries such as axios and webview, you must add instrumentation manually:
Axios network data collection
-
(Optional) To enable end-to-end distributed tracing, insert Alibaba Cloud's custom business request headers into each request. Skip this step if you do not need distributed tracing. If you use 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 API call results across 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:
-
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.
})