Skip to content

SDK Initialization

This document describes HarmonyOS SDK initialization and runtime capabilities.

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 a string: .setEnv('prod')
        .addGlobalContext('app_channel', new String('appgallery'))
        .setAutoSync(true)
        .setSyncPageSize(SyncPageSize.MEDIUM)
        .setDataSyncRetryCount(5)
        .setSyncSleepTime(0)
        .setCompressIntakeRequests(true);

      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 Type Required Description
datakitUrl string Yes Report URL for local environment deployment (DataKit), e.g., http://10.0.0.1:9529, default port 9529. The device where the SDK is installed must be able to access this address. Note: configure either datakitUrl or datawayUrl
datawayUrl string Yes Public DataWay report URL, obtained from the [Real User Monitoring (RUM)] application, e.g., https://open.dataway.url. The device where the SDK is installed 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. Defaults to false
setSdkLogLevel SDKLogLevel No Sets the SDK internal log output level. For details, see Troubleshooting
setEnableInnerLogFile enable: boolean, config?: FTInnerLogFileConfig No Whether to write SDK internal logs to a local file. Defaults to false. For details, see Troubleshooting
setEnv string \| EnvType No Environment. Defaults to prod. Accepts an EnvType enum or a string
setServiceName string No Business or service name. Defaults to df_rum_harmonyos
addGlobalContext key: string, value: object No Adds SDK global attributes. For the addition rules, see here
setAutoSync boolean No Whether to automatically sync data to the server after collection. Defaults to true. When set to false, you can use FTSDK.flushSyncData() to manage data synchronization yourself
setSyncPageSize SyncPageSize No Sets the predefined number of entries per sync request: MINI is 5, MEDIUM is 10, LARGE is 50. Defaults to SyncPageSize.MEDIUM
setCustomSyncPageSize number No Custom number of entries per sync request. Range [5, 500], rounded down, defaults to 10. Configure either this or setSyncPageSize
setDataSyncRetryCount number No Sets the maximum number of retries for a single data sync. Range [0, 5], rounded down, defaults to 5
setSyncSleepTime number No Sets the interval between consecutive sync requests. Range [0, 5000], in milliseconds, defaults to 0
setCompressIntakeRequests boolean No Whether to compress uploaded data with zlib-wrapped deflate. Defaults to true; falls back to plaintext upload when compression is unavailable
setProxy FTProxyConfig \| null No Sets the HTTP proxy used by SDK data upload requests; pass null to clear the proxy configuration
setProxyAuthenticator FTProxyAuthenticator \| null No Sets authentication information for the upload proxy; pass null to clear the standalone authentication configuration
setDns FTDnsConfig \| null No Sets the DNS server or DNS over HTTPS address used by SDK data upload requests; pass null to clear the DNS configuration
setDataModifier DataModifier \| null No Modifies or masks a single field. The original value is retained when null is returned. For details, see Data Masking
setLineDataModifier LineDataModifier \| null No Batch modifies or masks existing fields of a single data record. For details, see Data Masking
setEnableDataFilter boolean No Whether to enable DataKit-compatible local and remote blacklist filtering. Defaults to true. Supports filtering Logging and RUM data. For details, see Blacklist Filtering
setDataFilters FTDataFilters \| null No Sets local blacklist filtering rules; supports logging and rum rules. Pass null to clear the local rules. For details, see Blacklist Filtering
setEnableAccessDeviceID boolean No Whether to use the system device identifier as device_uuid. Defaults to false. When disabled, the SDK uses a persisted privacy UUID
setRemoteConfiguration boolean No Whether to enable remote configuration for data collection. Defaults to false. When enabled, the SDK fetches the configuration after the RUM configuration is installed and a valid report URL is available
setRemoteConfigMiniUpdateInterval number No Sets the minimum interval for data updates, in seconds. Defaults to 12 hours
setRemoteConfigurationCallBack FTRemoteConfigFetchResult \| null No Remote configuration result callback. See the code example
setNeedTransformOldCache boolean No Whether to migrate old cached data. Defaults to false. Enable it when switching to FileStore for the first time and retaining the existing SQLite cache is needed. Supported in ft-sdk 0.1.17 and later.
enableFileDataStore Void No Enables the file cache for sync cache and RUM aggregation data. SQLite cache is still used by default. Supported in ft-sdk 0.1.17 and later.
setUseFileDataStore boolean No Sets whether to use the file cache. Pass true to use FileStore, pass false to use the default SQLite cache. Supported in ft-sdk 0.1.17 and later.
setFileDataStoreShadow boolean No Enables shadow writes to the file cache. When enabled, reads and uploads still use SQLite while writes are mirrored to FileStore, for validation before migration. Supported in ft-sdk 0.1.17 and later.
enableLimitWithCacheSize cacheSize?: number No Enables the total cache size limit. Defaults to 100MB, in bytes; the minimum value accepted is 30MB. When enabled, the Log and RUM entry count limits no longer apply. Supported in ft-sdk 0.1.17 and later.
setCacheDiscard CacheDiscard No Sets the discard policy after the cache reaches the size limit. Defaults to CacheDiscard.DISCARD. DISCARD discards newly added data, DISCARD_OLDEST deletes the oldest cached data. Supported in ft-sdk 0.1.17 and later.
enableLimitWithDbSize cacheSize?: number No Deprecated. Kept for compatibility with older versions. Use enableLimitWithCacheSize instead.
setDbCacheDiscard DBCacheDiscard No Deprecated. Kept for compatibility with older versions. Use setCacheDiscard instead.

For how to use dynamic configuration and runtime updates of the report address, see Dynamic Configuration and Dynamic Address Updates.

File Cache

ft-sdk 0.1.17 and later support writing sync cache and RUM aggregation data to the file cache. To ensure a smooth upgrade, the SDK still uses the SQLite cache by default. If you need the file cache, you can explicitly enable it in FTSDKConfig.

const sdkConfig = FTSDKConfig.builder(datawayUrl, clientToken)
  .enableFileDataStore();

To first verify the file cache writes, you can enable shadow writes. When enabled, the SDK still reads and uploads data from SQLite while mirroring writes to FileStore. After validation passes, switch to enableFileDataStore().

const shadowConfig = FTSDKConfig.builder(datawayUrl, clientToken)
  .setFileDataStoreShadow(true);

Cache Size Limit

For ft-sdk 0.1.17 and later, it is recommended to use enableLimitWithCacheSize to configure the SDK total cache size limit. When enabled, the individual log entry count limit FTLoggerConfig.setLogCacheLimitCount and the RUM entry count limit FTRUMConfig.setRumCacheLimitCount no longer take effect.

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

const sdkConfig = FTSDKConfig.builder(datawayUrl, clientToken)
  // Enable the total cache size limit. Example: 100MB.
  .enableLimitWithCacheSize(100 * 1024 * 1024)
  // Delete the oldest cached data when the cache reaches the limit.
  .setCacheDiscard(CacheDiscard.DISCARD_OLDEST);

Upload Network Configuration

setProxy(...), setProxyAuthenticator(...), and setDns(...) only affect the requests the SDK uses to upload data to DataKit or DataWay. They do not modify the network configuration of application 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 with setProxyAuthenticator(...)
password string No Proxy password; can also be configured separately with 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; 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 DataKit-compatible blacklist filtering, used to filter Logging and RUM data before it is written to the local cache. This capability is enabled by default and can be disabled with setEnableDataFilter(false).

Blacklist rules are divided into local rules and remote rules:

  • Local rules are configured with setDataFilters and support two rule categories: logging and rum.
  • When data filtering is enabled and a valid report URL exists, the SDK pulls remote logging and rum rules from DataKit or DataWay.
  • Local and remote rules both filter new data; data that matches a rule is not written to the local cache.
  • Data is first modified by LineDataModifier, and then blacklist filtering is applied based on the modified content.
  • Remote rules clean up matched cached data before upload; local rules only filter new data.
  • The SDK checks whether the remote rules have expired each time an upload task starts, and pulls them only after they expire.
  • When the server-side pull_interval is a numeric value, its unit is nanoseconds; for example, 10000000000 means 10 seconds. A string value "10" also means 10 seconds, and unit formats such as "10s", "2m", and "1h" are also supported. If it is missing or invalid, it is treated as 10 seconds.
  • When the server response content is unchanged, the SDK does not parse or apply the same rules again.

Rule expressions must be enclosed in {} and support the in, not in, match, and not match operators. 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, and class; the match operator 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 accepts 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. This does not affect server-side remote rules.
sdkConfig.setDataFilters(null);

When switching to a valid report URL at runtime, the SDK clears the remote rules from the old URL and pulls them again from the new URL; local rules are retained.

User Binding and Unbinding

Usage

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

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

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

UserData

Method Description Required Notes
setId Sets the user ID No
setName Sets the user name No
setEmail Sets the email No
setExts Sets user extensions No For the addition rules, see 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 Automatic Data Sync

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

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

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

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

FTSDKConfig.setAutoSync(...) sets the sync state at SDK initialization; FTSDK.setAutoSync(...) dynamically modifies the sync state after SDK initialization.

Manually Sync Data

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

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

FTSDK.flushSyncData();

When automatic sync is enabled, the SDK uses a 10-second aggregation window to merge data generated consecutively within a short period before uploading. flushSyncData() does not wait for this aggregation window: it first flushes the currently pending RUM and Log worker queues into the local sync cache as much as possible, then immediately schedules the upload task. If the queue flush fails, it still continues to attempt to trigger the upload.

Clear SDK Cache Data

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

await FTSDK.clearAllData();

clearAllData() deletes all unreported cached data, 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?