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 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 |
Required before upload, or use DataWay | URL for reporting to a local DataKit deployment, for example http://10.0.0.1:9529. The device must be able to access this address. You can supplement it at runtime; see Dynamic Endpoint Update |
datawayUrl |
string |
Required before upload, or use DataKit | Public DataWay reporting URL, obtained from the [Real User Monitoring (RUM)] application, for example https://open.dataway.url. You can supplement it at runtime; use either this or datakitUrl |
clientToken |
string |
Required in DataWay mode | Authentication token. Must be configured together with datawayUrl |
setDebug |
boolean |
No | Whether to enable SDK internal diagnostic logs. Default: false |
setSdkLogLevel |
SDKLogLevel |
No | Sets 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. You can pass an EnvType enum or a string |
setServiceName |
string |
No | Name of the associated business or service. Default: df_rum_harmonyos |
addGlobalContext |
key: string, value: object |
No | Adds a global SDK property. For adding rules, refer to this section |
setAutoSync |
boolean |
No | Whether to automatically sync collected data to the server. Default: true. After setting it 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, and LARGE is 50. Default: SyncPageSize.MEDIUM |
setCustomSyncPageSize |
number |
No | Custom number of entries per sync request. Range: [5, 500]; decimals are rounded down. Default: 10. Configure either this or setSyncPageSize |
setDataSyncRetryCount |
number |
No | Sets the maximum number of retries for a single data sync. Range: [0, 5]; decimals are rounded down. Default: 5 |
setSyncSleepTime |
number |
No | Sets the interval between consecutive sync requests. Range: [0, 5000], in milliseconds. Default: 0 |
setCompressIntakeRequests |
boolean |
No | Whether to use zlib-wrapped deflate compression for uploaded data. Default: true. If compression is unavailable, uploads fall back to plaintext |
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. Returning null preserves the original value. For details, refer to Data Collection Masking |
setLineDataModifier |
LineDataModifier \| null |
No | Performs batch modification or masking on existing fields of a single data record. For details, refer to Data Collection Masking |
setEnableDataFilter |
boolean |
No | Whether to enable local and remote blocklist filtering compatible with DataKit. Default: true. Supports filtering Logging and RUM data. For details, refer to Blocklist Filtering |
setDataFilters |
FTDataFilters \| null |
No | Sets local blocklist filtering rules. Supports logging and rum rule types. Pass null to clear local rules. For details, refer to Blocklist Filtering |
setAllowWebViewHost |
Array<string> \| null |
No | Configures the Host scope for WebView RUM and Replay to use the Bridge in a unified way. null allows all Hosts, an empty array disables Bridge collection, and a non-empty array matches specified Hosts and their subdomains. This configuration is used for Bridge selection and is not a page origin security validation mechanism |
setEnableAccessDeviceID |
boolean |
No | Whether to use the system device identifier as device_uuid. Default: false. When disabled, the SDK-persisted privacy UUID is used. For runtime switching, see Dynamically Enable and Disable Device Identifier |
setOnlySupportMainProcess |
boolean |
No | Whether to initialize only in the main process. Default: true. To monitor child processes, set it to false before installation |
setRemoteConfiguration |
boolean |
No | Whether to enable remote configuration for data collection. Default: false. When enabled, the SDK fetches configuration after RUM configuration is installed and a valid reporting address is available |
setRemoteConfigMiniUpdateInterval |
number |
No | Sets the minimum data update interval, in seconds. Default: 12 hours |
setRemoteConfigurationCallBack |
FTRemoteConfigFetchResult \| null |
No | Callback for remote configuration results. See the code example |
setNeedTransformOldCache |
boolean |
No | Whether to migrate old cache data. Default: false. Enable this when switching to FileStore for the first time and existing SQLite cache needs to be retained. Supported in ft-sdk 0.1.17 and later. |
enableFileDataStore |
Void |
No | Enables file cache for sync cache and RUM aggregated data. SQLite cache is still used by default. Supported in ft-sdk 0.1.17 and later. |
setUseFileDataStore |
boolean |
No | Sets whether to use 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 for file cache. When enabled, reads and uploads still use SQLite while writes are mirrored to FileStore for pre-migration validation. Supported in ft-sdk 0.1.17 and later. |
enableLimitWithCacheSize |
cacheSize?: number |
No | Enables the total cache size limit. Default: 100MB, in bytes; the minimum value is 30MB. When enabled, the entry count limits for Log and RUM no longer take effect. Supported in ft-sdk 0.1.17 and later. |
setCacheDiscard |
CacheDiscard |
No | Sets the discard policy when the cache reaches the size limit. Default: CacheDiscard.DISCARD. DISCARD discards new data, and DISCARD_OLDEST deletes the oldest cached data. Supported in ft-sdk 0.1.17 and later. |
enableLimitWithDbSize |
cacheSize?: number |
No | Deprecated and retained for compatibility with older versions. Use enableLimitWithCacheSize instead. |
setDbCacheDiscard |
DBCacheDiscard |
No | Deprecated and retained for compatibility with older versions. Use setCacheDiscard instead. |
For how to use dynamic configuration and update the reporting address at runtime, refer to Dynamic Configuration and Dynamic Endpoint Update.
File Cache¶
ft-sdk 0.1.17 and later support writing sync cache and RUM aggregated data to file cache. To ensure a smooth upgrade, the SDK still uses SQLite cache by default. To enable file cache, explicitly enable it in FTSDKConfig.
To verify file cache writes first, you can enable shadow writes. When enabled, the SDK still reads from and uploads data from SQLite while mirroring writes to FileStore. After validation, switch to enableFileDataStore().
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 separate log entry limit FTLoggerConfig.setLogCacheLimitCount and RUM entry 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 is 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 SDK requests for uploading 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 proxy exclusion rules |
username |
string |
No | Proxy username. It can also be configured separately through setProxyAuthenticator(...) |
password |
string |
No | Proxy password. It can also be configured separately through 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 FTProxyAuthenticator configuration 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 |
Blocklist Filtering¶
ft-sdk 0.1.15 supports blocklist filtering compatible with DataKit, which filters Logging and RUM data before data is written to local cache. This capability is enabled by default and can be disabled with setEnableDataFilter(false).
Blocklist rules are divided into local rules and remote rules:
- Local rules are configured through
setDataFiltersand supportloggingandrumrule types. - When data filtering is enabled and a valid reporting address exists, the SDK pulls remote
loggingandrumrules from DataKit or DataWay. - Local and remote rules filter new data together; data that matches a rule is not written to local cache.
- Data is first modified by
LineDataModifier, and then blocklist filtering is performed on the modified content. - Remote rules clear matching cached data before upload; local rules only filter new data.
- The SDK checks whether remote rules have expired when each upload task starts, and only pulls them after they expire.
- When the server-side
pull_intervalis a numeric value, the unit is nanoseconds; for example,10000000000means 10 seconds. A string numeric value"10"means 10 seconds, and unit formats such as"10s","2m", and"1h"are also supported. If missing or invalid, 10 seconds is used. - When the content returned by the server has not changed, the SDK does not repeatedly parse or apply the same rules.
Rule expressions must be written 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, and data type identifier fields such as source, measurement, and class are also supported; 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 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 blocklist filtering, but retain configured local rules.
sdkConfig.setEnableDataFilter(false);
// Clear configured local rules without affecting server-side remote rules.
sdkConfig.setDataFilters(null);
When switching to a valid reporting address at runtime, the SDK clears the remote rules of the old address and pulls them again from the new address; 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 | Note |
|---|---|---|---|
setId |
Sets the user ID | No | |
setName |
Sets the username | No | |
setEmail |
Sets the email address | No | |
setExts |
Sets user extensions | No | For adding 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 Automatic Data Sync¶
After SDK initialization, you can dynamically enable or disable automatic sync of cached data through FTSDK.setAutoSync(...). When disabled, the SDK still writes collected data to local cache but does not automatically trigger upload 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 during SDK initialization;FTSDK.setAutoSync(...)dynamically changes the sync state after SDK initialization.
Manually Sync Data¶
When automatic sync is disabled, you can manually trigger data sync:
When automatic sync is enabled, the SDK uses a 10-second aggregation window to merge data continuously generated within a short period before uploading. flushSyncData() does not wait for this aggregation window: it first attempts to flush the currently pending RUM and Log worker queues into the local sync cache, then immediately schedules an upload task. If queue flushing fails, it still continues to attempt to trigger an upload.
Clear SDK Cache Data¶
clearAllData() deletes all cached data that has not been reported, 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)