Skip to content

RUM Configuration

This document covers HarmonyOS RUM initialization configuration and manual collection capabilities.

Sampling field migration (ft_sdk >= 0.1.18): setSessionSamplingRate and setSessionOnErrorSamplingRate use floating-point percentages from 0 to 100; the legacy setSamplingRate and setSessionErrorSampleRate retain the 0 to 1 unit, so multiply values by 100 during migration. The new fields take precedence over the legacy fields only when explicitly set. Invalid values throw an exception and do not change the previous valid value. For versions earlier than this version, continue using the legacy methods; deprecation does not mean removal, and the legacy methods retain their original units and behavior.

RUM Initialization Configuration

import {
  DetectFrequency,
  DeviceMetricsMonitorType,
  ErrorMonitorType,
  FTSDK,
  FTRUMConfig
} from '@guancecloud/ft_sdk/Index';

const rumConfig = new FTRUMConfig()
  .setRumAppId('your-app-id')
  .setSessionSamplingRate(100)
  .setSessionOnErrorSamplingRate(0)
  .setEnableTraceUserAction(true)
  .setEnableTraceUserView(true)
  .setEnableTraceUserResource(true)
  .setEnableTrackAppUIBlock(true)
  .setEnableTrackAppANR(true)
  .setEnableTrackAppCrash(true)
  .setEnableTraceWebView(true)
  .setDeviceMetricsMonitorType(DeviceMetricsMonitorType.ALL, DetectFrequency.DEFAULT)
  .setExtraMonitorTypeWithError(ErrorMonitorType.ALL)
  .addGlobalContext('rum_channel', new String('official'));

FTSDK.installRUMConfig(rumConfig);
Method Name Type Required Description
setRumAppId string Yes RUM application ID, obtained from the [RUM] application
setSessionSamplingRate number No Sets the session sampling rate. The value range is [0,100]; 0 means no collection, 100 means full collection, the default value is 100, and decimals are supported. Applies to RUM data under the same session_id. Supported in ft_sdk 0.1.18 and later
setSessionOnErrorSamplingRate number No Sets the error sampling rate. When a session is not sampled by setSessionSamplingRate, if an error occurs during the session, data from the 1 minute before the error can be collected. The value range is [0,100]; 0 means no collection, 100 means full collection, the default value is 0, and decimals are supported. Supported in ft_sdk 0.1.18 and later
setSamplingRate number No Deprecated compatibility API. The value range is [0,1], and the default value is 1. Use setSessionSamplingRate instead
setSessionErrorSampleRate number No Deprecated compatibility API. The value range is [0,1], and the default value is 0. Use setSessionOnErrorSamplingRate instead
setEnableTraceUserAction boolean No Whether to enable automatic action tracking. Default false
setEnableTraceUserView boolean No Whether to enable page tracking. Default false
setEnableTraceUserResource boolean No Whether to enable resource tracking. Default false
setEnableTrackAppUIBlock boolean, number No Whether to enable UI jank detection. Default false. The second parameter blockDurationMs controls the detection time range [100,), in milliseconds, default 1000ms
setEnableTrackAppANR boolean No Whether to enable ANR monitoring. Default false
setEnableTrackAppCrash boolean No Whether to enable app crash monitoring. Default false. For Native Crash, depend on @guancecloud/ft_native
setEnableTraceWebView boolean No Whether to enable WebView RUM data collection. Default false. For full integration, see WebView Data Monitoring
setAllowWebViewHost Array<string> \| null No This method is deprecated. Use FTSDKConfig.setAllowWebViewHost(...) to uniformly configure the Host scope for WebView RUM and Replay. See SDK Initialization Configuration
setActionTrackingHandler FTActionTrackingHandler \| null No Sets the automatic Action handler. Returns HandlerAction custom name and properties; null skips collection; undefined keeps the default. Automatic Click filtering is supported from 0.1.16; behavior for cold and hot launch handling and custom return values is available in 0.1.18 and later. Requires enabling setEnableTraceUserAction(true). See Custom Data Collection Rules
setViewTrackingHandler handler: FTViewTrackingHandler \| null, type?: FTViewTrackingType No Sets the handler for Router, Navigation, or all automatic Views. Takes effect only after setEnableTraceUserView(true) is enabled. The handler receives FTViewTrackingContext; returning HandlerView can rename or add properties, and returning null skips collection. See Custom Data Collection Rules. Supported in ft-sdk 0.1.17 and later
setResourceUrlHandler FTInTakeUrlHandler No Sets the URL filter handler for automatic Resources. Collection is skipped when the handler returns true. Affects only automatic Resources from RCP, Axios, and NetworkKit; does not affect Trace Header injection or manual Resources. See Custom Data Collection Rules. Supported in ft-sdk 0.1.17 and later
setNetworkErrorHandler FTNetworkErrorHandler \| null No Sets the default error handler when automatic RCP, Axios, or NetworkKit requests have no HTTP response. It can retain the Resource and skip the derived Network Error. Supported from 0.1.18; see Local Network Failure Filtering
setDeviceMetricsMonitorType DeviceMetricsMonitorType, DetectFrequency (optional) No Sets View monitoring information and sampling frequency, and adds monitoring data during the View lifecycle. The first parameter can use bitwise OR to combine CPU, MEMORY, BATTERY, and FPS, or use ALL to enable all; TV devices do not support battery metrics. The second parameter is optional: DetectFrequency.DEFAULT (500ms), DetectFrequency.FREQUENT (100ms), or DetectFrequency.RARE (1000ms). If omitted, the current sampling frequency is used, with an initial value of DEFAULT; not collected by default. Supported in ft-sdk 0.1.16 and later
setDeviceMetricsDetectFrequency DetectFrequency No Legacy device metrics configuration method, retained only for source compatibility; can be used with the single-parameter setDeviceMetricsMonitorType(...). For new integrations, configure the collection type and frequency at once through setDeviceMetricsMonitorType(deviceMetricsMonitorType, detectFrequency)
setExtraMonitorTypeWithError ErrorMonitorType No Sets additional device metrics for Error events. You can use bitwise OR to combine CPU, MEMORY, and BATTERY, or use ALL to enable all; when enabled, CPU, memory, and battery-related fields are added to Error data, not collected by default. TV devices do not support battery metrics. For field descriptions, see Application Data Collection. Supported in ft-sdk 0.1.16 and later
addGlobalContext key: string, value: object No Adds custom RUM tags used to distinguish user monitoring data; for addition rules, see here
setRumCacheLimitCount number No RUM data cache count limit, default 100000, minimum 10000
setRumCacheDiscardStrategy RUMCacheDiscard No Sets the RUM discard policy when RUM data reaches the limit. Default is RUMCacheDiscard.DISCARD; DISCARD discards appended data, and DISCARD_OLDEST discards old data

RUM Manual Collection

Configure setEnableTraceUserAction, setEnableTraceUserView, setEnableTraceUserResource, setEnableTrackAppUIBlock, setEnableTrackAppCrash, and setEnableTrackAppANR in FTRUMConfig to enable automatic collection of Action, View, Resource, LongTask, and Error. For custom collection, report manually through FTRUMGlobalManager.

View

Usage

/**
 * Starts the View lifecycle.
 *
 * @param viewName View name.
 * @param property Optional extended properties.
 */
startView(viewName: string, property?: Record<string, object>): Promise<void>

/**
 * Stops the current View lifecycle.
 *
 * @param property Optional extended properties.
 */
stopView(property?: Record<string, object>): Promise<void>

/**
 * Updates the load time of the current View.
 *
 * @param loadTime Load time, in nanoseconds.
 */
updateLoadTime(loadTime: number): void

Code Example

import { FTRUMGlobalManager } from '@guancecloud/ft_sdk/Index';

@Entry
@Component
struct ProductPage {
  async aboutToAppear() {
    // Scenario 1 (choose one of Scenario 1 and Scenario 2)
    // await FTRUMGlobalManager.getInstance().startView('ProductPage');

    // Scenario 2: dynamic properties
    const viewProperty: Record<string, object> = {
      ft_key: new String('ft_value'),
      ft_key_will_change: new String('ft_value')
    };
    await FTRUMGlobalManager.getInstance().startView('ProductPage', viewProperty);
  }

  async aboutToDisappear() {
    // Scenario 1 (choose one of Scenario 1 and Scenario 2)
    // await FTRUMGlobalManager.getInstance().stopView();

    // Scenario 2: dynamic properties
    const stopViewProperty: Record<string, object> = {
      ft_key_will_change: new String('ft_value_change')
    }; // The value of ft_key_will_change is updated to ft_value_change when stopView is called
    await FTRUMGlobalManager.getInstance().stopView(stopViewProperty);
  }

  build() {
    Column() {
      Text('Product Page');
    }
  }
}

Action

Usage

/**
 * Adds a completed Action; this data is not associated with Error, Resource, or LongTask.
 *
 * @param actionName Action name.
 * @param actionType Action type, for example `click`.
 * @param durationOrProperty Optional. When a number is passed, it indicates duration (nanoseconds); when a Record is passed, it indicates extended properties.
 * @param property Optional. Pass extended properties only when the third parameter is a duration.
 */
addAction(
  actionName: string,
  actionType: string,
  durationOrProperty?: number | Record<string, object>,
  property?: Record<string, object>
): void

/**
 * Starts an Action; the SDK manages the end timing and associates Resource, LongTask, and Error data that occur nearby.
 *
 * @param actionName Action name.
 * @param actionType Action type, for example `click`.
 * @param property Optional extended properties.
 */
startAction(
  actionName: string,
  actionType: string,
  property?: Record<string, object>
): void

addAction(...) is used for an Action that is completed directly and cannot associate data such as Error, Resource, or LongTask. duration is in nanoseconds: the third parameter can directly pass extended properties; if both duration and extended properties need to be passed, pass them as the third and fourth parameters respectively.

For startAction(...), the SDK manages the end timing and associated data. Manual control APIs such as stopAction(...) and wait states are not currently provided.

Code Example

import { FTRUMGlobalManager } from '@guancecloud/ft_sdk/Index';

// Scenario 1:
FTRUMGlobalManager.getInstance().addAction('buy_button_click', 'click');

// Scenario 2: with extended properties
const actionProperty: Record<string, object> = {
  product_id: new String('product_id'),
  product_name: new String('product_name')
};
FTRUMGlobalManager.getInstance().addAction('buy_button_click', 'click', actionProperty);

// Scenario 1:
FTRUMGlobalManager.getInstance().startAction('buy_button_click', 'click');

// Scenario 2: with extended properties
const startActionProperty: Record<string, object> = {
  product_id: new String('product_id'),
  product_name: new String('product_name')
};
FTRUMGlobalManager.getInstance().startAction('buy_button_click', 'click', startActionProperty);

Error

Usage

/**
 * Reports an Error.
 *
 * @param log Error log or stack information.
 * @param message Message.
 * @param errorType Error type; can pass the `ErrorType` enum or a string.
 * @param state The application running state when the error occurred.
 * @param property Optional extended properties.
 */
addError(
  log: string,
  message: string,
  errorType: string | ErrorType,
  state: AppState,
  property?: Record<string, object> | null
): void

/**
 * Reports an Error with a specified occurrence time.
 *
 * @param log Error log or stack information.
 * @param message Message.
 * @param dateline Error occurrence time, in nanoseconds.
 * @param errorType Error type; can pass the `ErrorType` enum or a string.
 * @param state The application running state when the error occurred.
 * @param property Optional extended properties.
 */
addError(
  log: string,
  message: string,
  dateline: number,
  errorType: string | ErrorType,
  state: AppState,
  property?: Record<string, object> | null
): void

For custom Errors, use ErrorType.CUSTOM. dateline is the optional occurrence time, in nanoseconds;

Code Example

import { FTRUMGlobalManager, ErrorType, AppState } from '@guancecloud/ft_sdk/Index';
import { systemDateTime } from '@kit.BasicServicesKit';

// Scenario 1:
FTRUMGlobalManager.getInstance().addError('error log', 'error message', ErrorType.CUSTOM, AppState.RUN);

// Scenario 2: For delayed reporting, pass the actual time when the error occurred (unit: nanoseconds).
const errorTimeNs = systemDateTime.getTime(true);
FTRUMGlobalManager.getInstance().addError('error log', 'error message', errorTimeNs, ErrorType.CUSTOM, AppState.RUN);

// Scenario 3: with extended properties.
const errorProperty: Record<string, object> = {
  module: new String('checkout'),
  action: new String('submit_order')
};
FTRUMGlobalManager.getInstance().addError('error log', 'error message', ErrorType.CUSTOM, AppState.RUN, errorProperty);

LongTask

Usage

/**
 * Reports a LongTask.
 *
 * @param log Log or stack information at the time of the jank.
 * @param duration Jank duration, in nanoseconds.
 * @param property Optional extended properties.
 */
addLongTask(log: string, duration: number, property?: Record<string, string | number | boolean>): void

duration is in nanoseconds.

Code Example

import { FTRUMGlobalManager } from '@guancecloud/ft_sdk/Index';

const durationMs = 350;
const durationNs = durationMs * 1000000;
const stack = new Error('checkout render long task').stack ?? 'Stack trace not available';

// Scenario 1:
FTRUMGlobalManager.getInstance().addLongTask(stack, durationNs);

// Scenario 2: with extended properties.
const longTaskProperty: Record<string, string | number | boolean> = {
  module: 'checkout',
  operation: 'render_order_list',
  threshold_ms: 200
};
FTRUMGlobalManager.getInstance().addLongTask(stack, durationNs, longTaskProperty);

Resource

Usage

/**
 * Starts the Resource lifecycle.
 *
 * @param resourceId Unique resource identifier; must use the same value as `stopResource` and `addResource`.
 * @param property Optional extended properties.
 */
startResource(resourceId: string, property?: Record<string, object>): void

/**
 * Ends the Resource lifecycle.
 *
 * @param resourceId Unique resource identifier; should use the same value as `startResource`.
 * @param property Optional extended properties.
 */
stopResource(resourceId: string, property?: Record<string, object>): void

/**
 * Supplements the request, response, and network performance data of the Resource.
 *
 * @param resourceId Unique resource identifier; should use the same value as `startResource` and `stopResource`.
 * @param resourceParams Resource details, such as URL, request method, response status, response length, and extended properties.
 * @param netStatusBean Network performance data, such as DNS, TCP, TTFB, and response time.
 */
addResource(resourceId: string, resourceParams: ResourceParams, netStatusBean: NetStatusBean): void

Extended properties passed to startResource(...) and stopResource(...) are merged with properties in ResourceParams in call order. Set the resource status code and response length through ResourceParams; they are no longer passed as parameters to stopResource(...).

Code Example

import {
  FTRUMGlobalManager,
  ResourceParams,
  NetStatusBean
} from '@guancecloud/ft_sdk/Index';

const resourceId = 'https://api.example.com/data';

// Scenario 1:
// Request starts
FTRUMGlobalManager.getInstance().startResource(resourceId);

// After the request ends, supplement the request, response, and network performance data.
const resourceParams = new ResourceParams();
resourceParams.setUrl(resourceId);
resourceParams.setResourceStatus(200);
resourceParams.setResponseContentLength(1024);
resourceParams.resourceType = 'xhr';

// Optional: set transfer information (0.1.18 and later).
resourceParams.setRequestBodySize(128);
resourceParams.setRequestHeaderSize(256);
resourceParams.setHttpProtocol('HTTP/2');
resourceParams.setConnectionReuse(true);

const netStatusBean = new NetStatusBean();
netStatusBean.setResourceHostIP('192.168.1.1');
netStatusBean.setDNSTime(10000000);
netStatusBean.setTcpTime(20000000);
netStatusBean.setTTFB(50000000);
netStatusBean.setResponseTime(100000000);

FTRUMGlobalManager.getInstance().stopResource(resourceId);
FTRUMGlobalManager.getInstance().addResource(resourceId, resourceParams, netStatusBean);

// Scenario 2: with extended properties. The following is an independent request; when using it, replace the startResource and stopResource calls in Scenario 1.
const startResourceProperty: Record<string, object> = {
  request_source: new String('checkout')
};
FTRUMGlobalManager.getInstance().startResource(resourceId, startResourceProperty);

const stopResourceProperty: Record<string, object> = {
  response_cache: new Boolean(false)
};
FTRUMGlobalManager.getInstance().stopResource(resourceId, stopResourceProperty);

The unit for request header and request body size is bytes. You can also set the total request bytes directly through setRequestSize(...). For field descriptions, see Application Data Collection.

NetStatusBean Properties

NetStatusBean is used to supplement network performance data for manual Resource collection. All time parameters are in nanoseconds; *StartTime indicates the offset relative to the Resource start time. Unset time values default to -1 and are not written to the corresponding metrics.

Method Description
setDNSTime DNS resolution time
setDNSStartTime DNS resolution start offset
setTcpTime TCP connection time
setConnectStartTime TCP connection start offset
setSSLTime SSL/TLS handshake time
setSslStartTime SSL/TLS handshake start offset
setTTFB Wait time before the first byte arrives (TTFB)
setResponseTime Response transfer time
setFirstByteTime First-byte phase time
setFirstByteStartTime First-byte phase start offset
setDownloadTime Response download time
setDownloadTimeStart Response download start offset
setHoleRequestTime Entire request time (the API name retains the Hole spelling as defined by the SDK)
setResourceHostIP Resource server IP address

Resource Auto-Tracking

After setEnableTraceUserResource(true) is enabled, the SDK automatically tracks requests sent through RCP, Axios compatibility mode, or the @kit.NetworkKit HTTP interceptor.

When integrating @guancecloud/ft_sdk_ext, it is recommended to import public APIs uniformly from @guancecloud/ft_sdk_ext/Index and avoid deep paths like src/main/....

RCP Auto-Tracking Integration

After setEnableTraceUserResource is enabled in the RUM configuration, the SDK automatically collects Resource data for HTTP requests sent through RCP.

Starting from the current version, the SDK no longer automatically creates or holds a global RCP Session. Instead, it provides the following capabilities for your application to assemble itself:

  • RCPTraceInterceptor: Automatically injects Trace Headers
  • RCPResourceInterceptor: Automatically collects Resource data and performance metrics
  • createFTRCPInterceptors(): Returns the default RCP interceptor list, making it easy to merge with a custom SessionConfiguration
  • createFTRCPTrackConfig(): Quickly generates a SessionConfiguration with default interceptors and TracingConfiguration

Recommended integration: use the default SessionConfiguration factory function

import { rcp } from '@kit.RemoteCommunicationKit';
import { createFTRCPTrackConfig } from '@guancecloud/ft_sdk/Index';

const session = rcp.createSession(
  createFTRCPTrackConfig({
    baseAddress: 'https://api.example.com'
  })
);

// GET request
const request = new rcp.Request('/data', 'GET');
const response = await session.fetch(request);

// POST request
const headers: rcp.RequestHeaders = { 'Content-Type': 'application/json' };
const postRequest = new rcp.Request('/data', 'POST', headers, { name: 'test' });
const postResponse = await session.fetch(postRequest);

If the project imports through the SDK root entry, you can also use:

import { createFTRCPTrackConfig } from '@guancecloud/ft_sdk/Index';

Manually assemble interceptors

If you need full control over the Session configuration, you can also use the interceptors provided by the SDK directly:

import { rcp } from '@kit.RemoteCommunicationKit';
import { RCPTraceInterceptor, RCPResourceInterceptor } from '@guancecloud/ft_sdk/Index';

const session = rcp.createSession({
  baseAddress: 'https://api.example.com',
  interceptors: [
    new RCPTraceInterceptor(),
    new RCPResourceInterceptor()
  ],
  requestConfiguration: {
    tracing: {
      collectTimeInfo: true
    }
  }
});

TracingConfiguration notes:

  • collectTimeInfo: true: Recommended. The SDK relies on response.timeInfo to calculate performance metrics such as DNS, TCP, SSL, TTFB, and download time
  • incomingHeader / outgoingHeader: Optional, enabled by default
  • incomingData / outgoingData: Disabled by default to reduce additional overhead

HTTP Interceptor Integration

If your application uses http.createHttp() from @kit.NetworkKit to send requests, you can use the HTTP interceptor provided by @guancecloud/ft_sdk_ext to automatically inject Trace Headers and collect Resource data. This integration requires ft_sdk_ext 0.1.14 or later and HarmonyOS API 22 or later.

First, ensure the project has installed:

  • ft_sdk.har, and declare it as @guancecloud/ft_sdk in oh-package.json5
  • ft_sdk_ext.har, and declare it as @guancecloud/ft_sdk_ext in oh-package.json5
  • If you install ft_sdk_ext.har through a local HAR, you also need to add overrides["@guancecloud/ft_sdk"] = "file:./libs/ft_sdk.har" in oh-package.json5 at the project root to rewrite its internal dependency to the local HAR

The SDK provides the following capabilities:

  • HttpInitialRequestInterceptor: Injects the Trace Header at the request start phase and starts the Resource
  • HttpFinalResponseInterceptor: Supplements Resource data at the response end phase and ends collection
  • createFTHttpInterceptorChain(): Creates a reusable http.HttpInterceptorChain
  • applyFTHttpTrack(): Mounts the default interceptor chain directly to a single http.HttpRequest
  • disposeFTHttpTrack(request): Releases collection resources before canceling or destroying a request

Two integration methods are provided.

Method 1: Use the default factory provided by the SDK

import { http } from '@kit.NetworkKit';
import { createFTHttpInterceptorChain, disposeFTHttpTrack } from '@guancecloud/ft_sdk_ext/Index';

const request = http.createHttp();
const interceptorChain = createFTHttpInterceptorChain();
interceptorChain.apply(request);

try {
  const response = await request.request('https://httpbin.org/get', {
    method: http.RequestMethod.GET,
    header: {
      'Accept': 'application/json'
    }
  });
} finally {
  disposeFTHttpTrack(request);
  request.destroy();
}

If you want to append your own interceptors, you can also write it as follows:

import { http } from '@kit.NetworkKit';
import { createFTHttpInterceptorChain } from '@guancecloud/ft_sdk_ext/Index';

const request = http.createHttp();
const interceptorChain = createFTHttpInterceptorChain({
  interceptors: [
    new CustomAfterInterceptor() // Append custom
  ]
});
interceptorChain.apply(request);

In this case, the execution order is:

[
  new HttpInitialRequestInterceptor(),
  new HttpFinalResponseInterceptor(),
  new CustomAfterInterceptor()
]

Method 2: Manually assemble HttpInterceptorChain

If your application already has custom interceptors, or you need to freely determine the interceptor order, it is recommended to create an http.HttpInterceptorChain manually:

import { http } from '@kit.NetworkKit';
import {
  HttpInitialRequestInterceptor,
  HttpFinalResponseInterceptor
} from '@guancecloud/ft_sdk_ext/Index';

const request = http.createHttp();
const interceptorChain = new http.HttpInterceptorChain();
interceptorChain.addChain([
  new CustomBeforeInterceptor(),
  new HttpInitialRequestInterceptor(),
  new HttpFinalResponseInterceptor()
]);
interceptorChain.apply(request);

Notes:

  • The HTTP interceptor relies on the interceptor capability provided by @kit.NetworkKit in API 22+. For versions below API 22, use RCP or Axios compatibility mode instead
  • In the HTTP interceptor mode that directly uses http.createHttp(), HttpRequestContext currently cannot reliably obtain the real request method, so the method in Resource may be recorded as UNKNOWN
  • If your application uses the interceptorChain mode of @ohos/axios, it is recommended to additionally mount applyFTAxiosChainMethodBridge() to bridge the real method, url, and headers from axios

Axios Integration

If your application uses @ohos/axios, you can integrate auto-tracking as follows:

  • @guancecloud/ft_sdk: compatibility mode based on Axios request/response interceptors
  • @guancecloud/ft_sdk_ext: enhanced mode based on interceptorChain, available in 0.1.14 and later

@ohos/axios 2.2.4 and Later

This integration is based on Axios request/response interceptors.

import axios from '@ohos/axios';
import { applyFTAxiosTrack } from '@guancecloud/ft_sdk/Index';

const client = axios.create({
  timeout: 10000
});

applyFTAxiosTrack(client);

This integration can coexist with your own interceptors:

import axios from '@ohos/axios';
import { applyFTAxiosTrack } from '@guancecloud/ft_sdk/Index';

const client = axios.create({
  timeout: 10000
});

applyFTAxiosTrack(client);

client.interceptors.request.use((config) => {
  config.headers = {
    ...(config.headers || {}),
    Authorization: 'Bearer <token>',
    'X-Signature': 'signed-value'
  };
  return config;
});

client.interceptors.response.use((response) => {
  return response;
});

Execution order notes:

  • In @ohos/axios compat mode, request interceptors behave as follows: last registered, first executed
  • This means multiple request interceptors can coexist, but the registration order affects whether FT sees the request headers “before modification” or “after modification”
  • If you want FT to collect the final request headers after your application adds authentication, signature, and other fields, the recommended order is: call applyFTAxiosTrack(client) first, then register the application request interceptor
  • With the above order, the application request interceptor executes first, and FT executes afterward and reads the final headers
  • To change the order, simply change the registration order; for example, if you register the application interceptor first and then call applyFTAxiosTrack(client), FT executes first and the application interceptor executes afterward

@ohos/axios 2.2.8 and Later

For @ohos/axios 2.2.8 and later, it is recommended to integrate FT auto-tracking through the interceptorChain of @guancecloud/ft_sdk_ext first:

import axios from '@ohos/axios';
import {
  createFTHttpInterceptorChain,
  applyFTAxiosChainMethodBridge
} from '@guancecloud/ft_sdk_ext/Index';

const client = axios.create({
  timeout: 10000,
  interceptorChain: createFTHttpInterceptorChain()
});

applyFTAxiosChainMethodBridge(client);

const response = await client.post('https://api.example.com/data', {
  source: 'axios',
  message: 'ft auto track'
});

If multiple interceptors coexist, you need to manually adjust the execution order, or you need to assemble them together with custom application interceptors, refer to HTTP Interceptor Integration and combine HttpInitialRequestInterceptor and HttpFinalResponseInterceptor as needed.

If passing it per request, you can also write it as follows:

import axios from '@ohos/axios';
import { createFTHttpInterceptorChain } from '@guancecloud/ft_sdk_ext/Index';

const response = await axios.request({
  url: 'https://httpbin.org/post',
  method: 'post',
  data: {
    source: 'axios',
    message: 'ft auto track'
  },
  responseType: 'string',
  interceptorChain: createFTHttpInterceptorChain()
});

Notes:

  • It is recommended to inject interceptorChain uniformly when creating an Axios instance and call applyFTAxiosChainMethodBridge(client) to avoid inaccurate Resource method recording caused by missing the bridge.
  • The interceptorChain mode depends on @guancecloud/ft_sdk_ext (the local HAR file name remains ft_sdk_ext.har) and requires HarmonyOS API 22+
  • To automatically inject Trace Headers, in addition to creating the interceptor chain, you also need to enable setEnableAutoTrace(true) in the Trace configuration
  • To automatically collect Resource, you still need to enable setEnableTraceUserResource(true) in the RUM configuration
  • If the caller already has custom HTTP/Axios interceptors, it is recommended to use HttpInitialRequestInterceptor and HttpFinalResponseInterceptor to manually assemble the order, avoiding rewriting url, method, or headers again after FT auto-tracking
  • The SDK only provides interceptors and default configuration factory functions; the creation and lifecycle of RCP Sessions are managed by your application
  • If your application directly uses rcp.createSession() to create a Session, you need to add the interceptors provided by the SDK yourself; otherwise, requests are not automatically tracked
  • If your application directly uses http.createHttp() or @ohos/axios, you need to explicitly mount applyFTHttpTrack(), applyFTAxiosTrack(), or createFTHttpInterceptorChain(); the Axios interceptorChain mode also requires calling applyFTAxiosChainMethodBridge(client)

Resource Performance Metrics

RCP uses response.timeInfo, while NetworkKit HTTP and Axios using its network adapter use performanceTiming to obtain performance data. The following time points are in milliseconds, and calculation results are uniformly converted to nanoseconds for reporting.

Metric RCP TimeInfo NetworkKit performanceTiming
DNS time nameLookupTimeMs dnsTiming
TCP time tlsHandshakeTimeMs - nameLookupTimeMs; when no valid TLS time point, connectTimeMs - nameLookupTimeMs tlsTiming - dnsTiming; when no valid TLS time point, tcpTiming - dnsTiming
SSL time tlsHandshakeTimeMs - connectTimeMs tlsTiming - tcpTiming
TTFB startTransferTimeMs - preTransferTimeMs firstReceiveTiming - firstSendTiming
Download time totalTimeMs - startTransferTimeMs totalFinishTiming - firstReceiveTiming

If a phase time point is missing or invalid, the corresponding phase metric is not reported.

Feedback

Is this page helpful?