Skip to content

SDK Initialization

This document covers the initialization and runtime capabilities of the HarmonyOS SDK.

Basic Configuration

Initialize the SDK in EntryAbility.ets:

import { AbilityConstant, UIAbility, Want } from '@kit.AbilityKit';
import { hilog } from '@kit.PerformanceAnalysisKit';
import { FTSDK, FTSDKConfig, EnvType, SDKLogLevel, SyncPageSize} from '@guancecloud/ft_sdk/Index';

const DOMAIN = 0x0000;

export default class EntryAbility extends UIAbility {
  onCreate(want: Want, launchParam: AbilityConstant.LaunchParam): void {
    this.initFTSDK();
  }

  private initFTSDK(): void {
    try {
      // Local environment deployment (Datakit)
      // const sdkConfig = FTSDKConfig.builder(datakitUrl);

      // Public network DataWay
      const sdkConfig = FTSDKConfig.builder(datawayUrl, clientToken)
        .setDebug(true)
        .setSdkLogLevel(SDKLogLevel.D)
        .setServiceName('Your-App-Name')
        .setEnv(EnvType.PROD) // Or use string: .setEnv('prod')
        .setAutoSync(true)
        .setSyncPageSize(SyncPageSize.MEDIUM)
        .setDataSyncRetryCount(5)
        .setSyncSleepTime(0)
        .setCompressIntakeRequests(true);
        // To enable DB cache size limit, call .enableLimitWithDbSize(); if dbSize is not passed, default is 100MB

      FTSDK.install(sdkConfig, this.context);
      hilog.info(DOMAIN, 'FTSDK', 'FT SDK initialized successfully');
    } catch (error) {
      const errorObj: object = error as object;
      hilog.error(DOMAIN, 'FTSDK', `Failed to initialize FT SDK: ${JSON.stringify(errorObj)}`);
    }
  }
}
Method Name Type Required Description
datakitUrl string Yes URL for local environment deployment (DataKit) reporting, e.g., http://10.0.0.1:9529, default port 9529. The device installing the SDK must be able to access this address. Note: Configure either datakitUrl or datawayUrl
datawayUrl string Yes URL for public network DataWay reporting, obtained from the [RUM] application, e.g., https://open.dataway.url. The device installing the SDK must be able to access this address. Note: Configure either datakitUrl or datawayUrl
clientToken string Yes Authentication token, must be configured together with datawayUrl
setDebug boolean No Whether to enable SDK internal diagnostic logs, default false
setSdkLogLevel SDKLogLevel No Set the SDK internal log output level. For details, refer to Troubleshooting
setEnableInnerLogFile enable: boolean, config?: FTInnerLogFileConfig No Whether to write SDK internal logs to a local file, default false. For details, refer to Troubleshooting
setEnv string \| EnvType No Environment, default prod. Can be an EnvType enum or a string
setServiceName string No Service or business name, default df_rum_harmonyos
setAutoSync boolean No Whether to automatically sync data to the server after collection, default true. When set to false, use FTSDK.flushSyncData() to manage data sync manually
setSyncPageSize SyncPageSize No Set the predefined number of sync request entries: MINI is 5, MEDIUM is 10, LARGE is 50, default SyncPageSize.MEDIUM
setCustomSyncPageSize number No Custom number of sync request entries, range [5, 500], decimals are truncated, default 10. Mutually exclusive with setSyncPageSize
setDataSyncRetryCount number No Set the maximum retry count for a single data sync, range [0, 5], decimals are truncated, default 5
setSyncSleepTime number No Set the interval between consecutive sync requests, range [0, 5000], in milliseconds, default 0
setCompressIntakeRequests boolean No Whether to compress upload data using zlib's deflate, default true; if compression is unavailable, it falls back to plain text upload
setProxy FTProxyConfig \| null No Set the HTTP proxy for SDK data upload requests; pass null to clear the proxy configuration
setProxyAuthenticator FTProxyAuthenticator \| null No Set the authentication information for the upload proxy; pass null to clear the independent authentication configuration
setDns FTDnsConfig \| null No Set the DNS server or DNS over HTTPS address for SDK data upload requests; pass null to clear the DNS configuration
setDataModifier DataModifier \| null No Modify or mask a single field, returns null to retain the original value. For details, refer to Data Masking
setLineDataModifier LineDataModifier \| null No Batch modify or mask existing fields in a single data item. For details, refer to Data Masking
setEnableDataFilter boolean No Whether to enable local and remote blacklist filtering compatible with DataKit, default true. Supports filtering Logging and RUM data. For details, refer to Blacklist Filtering
setDataFilters FTDataFilters \| null No Set local blacklist filtering rules; supports logging and rum rule types. Pass null to clear local rules. For details, refer to Blacklist Filtering
setEnableAccessDeviceID boolean No Whether to use the system device identifier as device_uuid, default false. When disabled, the SDK uses a persistent privacy UUID
setRemoteConfiguration boolean No Whether to enable remote configuration for data collection, default false. When enabled, the SDK fetches the configuration after the RUM configuration is installed and a valid reporting address is available
setRemoteConfigMiniUpdateInterval number No Set the minimum update interval for data, in seconds, default 12 hours
setRemoteConfigurationCallBack FTRemoteConfigFetchResult \| null No Remote configuration result callback. Refer to Code Example
enableLimitWithDbSize number No Enable the DB cache size limit, default 100MB, in bytes. When passing dbSize, the range is [30MB,). After enabling, FTLoggerConfig.setLogCacheLimitCount and FTRUMConfig.setRumCacheLimitCount will become invalid.
setDbCacheDiscard DBCacheDiscard No Set the discard strategy when the DB cache reaches the size limit, default is DBCacheDiscard.DISCARD. DISCARD discards newly appended data, DISCARD_OLDEST deletes the oldest cached data.

For dynamic configuration and runtime update of the reporting address, refer to Dynamic Configuration and Dynamic Address Update.

Upload Network Configuration

setProxy(...), setProxyAuthenticator(...), and setDns(...) only affect the SDK's requests to upload data to DataKit or DataWay, and do not modify the network configuration of the application's business requests.

import {
  FTSDK,
  FTSDKConfig,
  FTProxyConfig,
  FTProxyAuthenticator,
  FTDnsConfig
} from '@guancecloud/ft_sdk/Index';

const proxyConfig: FTProxyConfig = {
  host: 'proxy.example.com',
  port: 8080,
  exclusionList: ['localhost', '127.0.0.1']
};

const proxyAuthenticator: FTProxyAuthenticator = {
  username: 'proxy-user',
  password: 'proxy-password'
};

const dnsConfig: FTDnsConfig = {
  servers: ['1.1.1.1', '8.8.8.8'],
  overHttpsUrl: 'https://dns.example.com/dns-query'
};

const sdkConfig = FTSDKConfig.builder(datawayUrl, clientToken)
  .setProxy(proxyConfig)
  .setProxyAuthenticator(proxyAuthenticator)
  .setDns(dnsConfig);

FTSDK.install(sdkConfig, this.context);

FTProxyConfig

Field Type Required Description
host string Yes Proxy server address
port number Yes Proxy server port
exclusionList Array<string> No List of hosts that do not use the proxy, following NetworkKit's proxy exclusion rules
username string No Proxy username; can also be configured separately via setProxyAuthenticator(...)
password string No Proxy password; can also be configured separately via setProxyAuthenticator(...)

FTProxyAuthenticator

Field Type Required Description
username string Yes Proxy authentication username
password string Yes Proxy authentication password

If authentication information is set in both FTProxyConfig and FTProxyAuthenticator, the configuration in FTProxyAuthenticator takes precedence.

FTDnsConfig

Field Type Required Description
servers Array<string> No Custom DNS server addresses. Empty strings are ignored, and at most the first three valid addresses are used
overHttpsUrl string No DNS over HTTPS service address

Blacklist Filtering

ft-sdk 0.1.15 supports blacklist filtering compatible with DataKit, used to filter Logging and RUM data before writing to the local cache. This feature is enabled by default and can be disabled via setEnableDataFilter(false).

Blacklist rules are divided into local rules and remote rules:

  • Local rules are configured via setDataFilters, supporting logging and rum rule types.
  • When data filtering is enabled and a valid reporting address exists, the SDK pulls remote logging and rum rules from DataKit or DataWay via /v1/datakit/pull?filters=true.
  • Local rules and remote rules take effect simultaneously. If either rule is matched, the data item is discarded and will not be written to the local cache or uploaded.
  • Blacklist filtering is executed after LineDataModifier and before writing to the local cache. If both setLineDataModifier and blacklist filtering are configured, the filtering rules will be applied to the modified data.

Rule expressions must be enclosed in {}, supporting operators in, not in, match, not match. Multiple conditions can be combined with and / or. Field sources include data tags and fields, as well as data type identifier fields such as source, measurement, class; match uses regular expressions.

import {
  FTSDK,
  FTSDKConfig,
  FTDataFilters
} from '@guancecloud/ft_sdk/Index';

const dataFilters: FTDataFilters = new Map<string, Array<string>>();
dataFilters.set('logging', [
  "{ source in ['df_rum_harmonyos_log'] and message match ['.*password.*'] }"
]);
dataFilters.set('rum', [
  "{ source in [resource] and resource_status in ['404', '503'] }"
]);

const sdkConfig = FTSDKConfig.builder(datawayUrl, clientToken)
  .setEnableDataFilter(true)
  .setDataFilters(dataFilters);

FTSDK.install(sdkConfig, this.context);

FTDataFilters can accept either a Map<string, Array<string>> or an object with the same structure. Category names are case-insensitive; categories other than logging and rum are ignored.

// Disable local and remote blacklist filtering, but keep the configured local rules.
sdkConfig.setEnableDataFilter(false);

// Clear the configured local rules without affecting server-side remote rules.
sdkConfig.setDataFilters(null);

The interval for pulling remote rules is determined by the pull_interval returned by the server; if the server does not return a valid value, the SDK uses a fallback interval of 10 seconds. pull_interval supports seconds or a string with a unit, e.g., 10, 30s, 2m, 1h. When the runtime switches to a valid reporting address, the SDK clears the remote rules from the old address and immediately re-fetches from the new address; local rules are retained.

User Binding and Unbinding

Usage

/**
 * Bind user information (user ID only)
 * @param id User ID
 */
static bindRumUserDataById(id: string): void

/**
 * Bind user information (full user data)
 * @param userData User data object
 */
static bindRumUserData(userData: UserData): void

/**
 * Unbind user information
 */
static unbindRumUserData(): void

UserData

Method Name Description Required Notes
setId Set user ID No
setName Set user name No
setEmail Set email No
setExts Set user extensions No For addition rules, refer to Custom Tags and Global Context

Code Example

import { FTSDK, UserData } from '@guancecloud/ft_sdk/Index';

// Method 1: Bind only the user ID (recommended for quick binding)
FTSDK.bindRumUserDataById('user_001');

const userData = new UserData();
userData.setId('user_001');
userData.setName('test.user');
userData.setEmail('test@mail.com');
userData.setExts({
  'user_type': 'vip'
});
FTSDK.bindRumUserData(userData);

FTSDK.unbindRumUserData();

Runtime Capabilities

Set Auto Sync Data

After SDK initialization, you can dynamically enable or disable automatic sync of cached data via FTSDK.setAutoSync(...). When disabled, the SDK will still write collected data to the local cache but will not automatically trigger uploads after collection; you can use FTSDK.flushSyncData() to manage data sync manually.

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

// Disable auto sync
FTSDK.setAutoSync(false);

// Enable auto sync
FTSDK.setAutoSync(true);

FTSDKConfig.setAutoSync(...) is used to set the sync state during SDK initialization; FTSDK.setAutoSync(...) is used to dynamically change the sync state after SDK initialization.

Manually Sync Data

When auto sync is disabled, you can manually trigger data sync:

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

FTSDK.flushSyncData();

When auto sync is enabled, the SDK uses a 10-second aggregation window to merge data generated within a short period before uploading. flushSyncData() does not wait for this aggregation window: it first tries to flush the currently pending RUM and Log worker queues into the local sync cache, then immediately schedules an upload task; if the queue flush fails, it still attempts to trigger the upload.

Clear SDK Cache Data

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

await FTSDK.clearAllData();

clearAllData() deletes all cached data that has not been uploaded, including:

  • All data in the sync data table (sync_data_flat)
  • All data in the RUM view data table (rum_view)
  • All data in the RUM action data table (rum_action)

Feedback

Is this page helpful? ×