React Native App Integration¶
Prerequisites¶
Note
If the RUM Headless service has been activated, the prerequisites are automatically configured, and the app can be directly integrated.
- Install DataKit;
- Configure the RUM Collector;
- Configure DataKit to be accessible over the public network and install the IP geolocation database.
App Integration¶
Note
The current React Native version only supports Android and iOS platforms.
- Go to RUM > Create Application > React Native;
- Create two separate applications for React Native Android and React Native iOS to receive RUM data from the Android and iOS platforms respectively;
- Enter the corresponding application name and application ID for each platform's application;
- Choose the application integration method:
- Public DataWay: Directly receives RUM data without installing the DataKit collector.
- Local Environment Deployment: Receives RUM data after meeting the prerequisites.
Installation¶
Source Code Repository: https://github.com/GuanceCloud/datakit-react-native
Demo Repository: https://github.com/GuanceCloud/datakit-react-native/example
In the project directory, run the following command in the terminal:
This will add a line like this to the package.json file:
Additional Configuration for Android Integration:
- Configure the Gradle Plugin ft-plugin to collect App startup events, network request data, and Android Native related events (page navigation, click events, Native network requests, WebView data).
- Note: You also need to configure the TrueWatch Android Maven repository address in Gradle. Both the Plugin and AAR require this configuration. Refer to the configuration details in the example's build.gradle.
Now in your code, you can use:
import {
FTMobileReactNative,
FTReactNativeLog,
FTReactNativeTrace,
FTReactNativeRUM,
FTMobileConfig,
FTLogConfig,
FTTraceConfig,
FTRUMConfig,
ErrorMonitorType,
DeviceMetricsMonitorType,
DetectFrequency,
TraceType,
FTLogStatus,
EnvType,
} from '@cloudcare/react-native-mobile';
SDK Initialization¶
Basic Configuration¶
//Local environment deployment, Datakit deployment
let config: FTMobileConfig = {
datakitUrl: datakitUrl,
};
//Use public DataWay
let config: FTMobileConfig = {
datawayUrl: datawayUrl,
clientToken: clientToken
};
await FTMobileReactNative.sdkConfig(config);
| Field | Type | Required | Description |
|---|---|---|---|
| datakitUrl | string | Yes | The reporting URL address for local environment deployment (Datakit), e.g., http://10.0.0.1:9529. The default port is 9529. The device installing the SDK must be able to access this address. Note: Choose one between datakitUrl and datawayUrl configuration. |
| datawayUrl | string | Yes | The reporting URL address for public DataWay. Obtain this from the [RUM] application, e.g., https://open.dataway.url. The device installing the SDK must be able to access this address. Note: Choose one between datakitUrl and datawayUrl configuration. |
| clientToken | string | Yes | Authentication token, must be used together with datawayUrl. |
| debug | boolean | No | Sets whether to allow log printing. Default is false. |
| env | string | No | Environment configuration. Default is prod. Can be any string, recommended to use a single word like test. |
| envType | enum EnvType | No | Environment configuration. Default is EnvType.prod. Note: Only one of env or envType needs to be configured. |
| service | string | No | Sets the name of the associated business or service, affecting the service field data in Log and RUM. Defaults: df_rum_ios, df_rum_android. |
| autoSync | boolean | No | Whether to automatically sync collected data to the server. Default is true. When false, use FTMobileReactNative.flushSyncData() to manage data synchronization manually. |
| syncPageSize | number | No | Sets the number of entries per sync request. Range [5,). Note: A larger number of request entries means the data synchronization consumes more computing resources. |
| syncSleepTime | number | No | Sets the sync interval time. Range [0,5000] milliseconds. Default is not set. |
| enableDataIntegerCompatible | boolean | No | Recommended to enable when coexisting with web data. This configuration handles web data type storage compatibility issues. Enabled by default in versions after 0.3.12. |
| globalContext | object | No | Adds custom tags. Refer to the rules for adding here. |
| compressIntakeRequests | boolean | No | Compresses upload sync data using deflate. Disabled by default. |
| enableLimitWithDbSize | boolean | No | Enables limiting data size using the database. Default is 100MB, unit Byte. A larger database increases disk pressure. Disabled by default. Note: After enabling, the Log configuration logCacheLimitCount and RUM configuration rumCacheLimitCount become invalid. Supported in SDK version 0.3.10 and above. |
| dbCacheLimit | number | No | DB cache limit size. Range [30MB,), default 100MB, unit byte. Supported in SDK version 0.3.10 and above. |
| dbDiscardStrategy | string | No | Sets the data discard rule for the database. Discard strategies: FTDBCacheDiscard.discard discards new data (default), FTDBCacheDiscard.discardOldest discards old data. Supported in SDK version 0.3.10 and above. |
| dataModifier | object | No | Modifies individual fields. Supported in SDK version 0.3.14 and above. See usage example here. |
| lineDataModifier | object | No | Modifies single data entries. Supported in SDK version 0.3.14 and above. See usage example here. |
RUM Configuration¶
let rumConfig: FTRUMConfig = {
androidAppId: Config.ANDROID_APP_ID,
iOSAppId:Config.IOS_APP_ID,
enableAutoTrackUserAction: true,
enableAutoTrackError: true,
enableNativeUserAction: true,
enableNativeUserView: false,
enableNativeUserResource: true,
errorMonitorType:ErrorMonitorType.all,
deviceMonitorType:DeviceMetricsMonitorType.all,
detectFrequency:DetectFrequency.rare
};
await FTReactNativeRUM.setConfig(rumConfig);
| Field | Type | Required | Description |
|---|---|---|---|
| androidAppId | string | Yes | app_id, applied for in the RUM console. |
| iOSAppId | string | Yes | app_id, applied for in the RUM console. |
| sampleRate | number | No | Sampling rate, range [0,1]. 0 means no collection, 1 means full collection. Default is 1. Scope: all View, Action, LongTask, Error data under the same session_id. |
| sessionOnErrorSampleRate | number | No | Sets the error collection rate. When a session is not sampled by sampleRate, if an error occurs during the session, data from 1 minute before the error can be collected. Range [0,1]. 0 means no collection, 1 means full collection. Default is 0. Scope: all View, Action, LongTask, Error data under the same session_id. Supported in SDK version 0.3.14 and above. |
| enableAutoTrackUserAction | boolean | No | Whether to automatically collect React Native component click events. After enabling, can be used with accessibilityLabel to set actionName. For more custom operations, refer to here. |
| enableAutoTrackError | boolean | No | Whether to automatically collect React Native Errors. Default is false. |
| enableNativeUserAction | boolean | No | Whether to track Native Action, native Button click events, app startup events. Default is false. |
| enableNativeUserView | boolean | No | Whether to enable Native View auto-tracking. Recommended to disable for pure React Native apps. Default is false. |
| enableNativeUserResource | boolean | No | Whether to enable Native Resource auto-tracking. Since React-Native network requests are implemented using system APIs on iOS and Android, enabling enableNativeUserResource allows all resource data to be collected together. Default is false. |
| errorMonitorType | enum ErrorMonitorType | No | Sets auxiliary monitoring information, adding additional monitoring data to RUM Error data. ErrorMonitorType.battery for battery level, ErrorMonitorType.memory for memory usage, ErrorMonitorType.cpu for CPU usage. Not enabled by default. |
| deviceMonitorType | enum DeviceMetricsMonitorType | No | Adds monitoring data during the View cycle. DeviceMetricsMonitorType.battery (Android only) monitors the maximum current output on the current page, DeviceMetricsMonitorType.memory monitors the current app memory usage, DeviceMetricsMonitorType.cpu monitors CPU ticks, DeviceMetricsMonitorType.fps monitors screen frame rate. Not enabled by default. |
| detectFrequency | enum DetectFrequency | No | Sampling frequency for view performance monitoring. Default is DetectFrequency.normal. |
| enableResourceHostIP | boolean | No | Whether to collect the IP address of the requested target domain. Scope: Only affects the default collection when enableNativeUserResource is true. iOS: Supported on >= iOS 13. Android: A single Okhttp has an IP caching mechanism for the same domain. Under the same OkhttpClient, if the server IP does not change, it will only be generated once. |
| globalContext | object | No | Adds custom tags for user monitoring data source differentiation. If tracing functionality is needed, set the parameter key to track_id and value to any number. Refer to the rules and precautions for adding here. |
| enableTrackNativeCrash | boolean | No | Whether to enable monitoring of Android Java Crash and OC/C/C++ crashes. Default is false. |
| enableTrackNativeAppANR | boolean | No | Whether to enable Native ANR monitoring. Default is false. |
| enableTrackNativeFreeze | boolean | No | Whether to collect Native Freeze. Default is false. |
| nativeFreezeDurationMs | number | No | Sets the threshold for collecting Native Freeze stalls. Range [100,), unit milliseconds. iOS default 250ms, Android default 1000ms. |
| rumDiscardStrategy | string | No | Discard strategy: FTRUMCacheDiscard.discard discards new data (default), FTRUMCacheDiscard.discardOldest discards old data. |
| rumCacheLimitCount | number | No | Local cache maximum RUM entry count limit [10_000,), default 100_000. |
Log Configuration¶
let logConfig: FTLogConfig = {
enableCustomLog: true,
enableLinkRumData: true,
};
await FTReactNativeLog.logConfig(logConfig);
| Field | Type | Required | Description |
|---|---|---|---|
| sampleRate | number | No | Sampling rate, range [0,1]. 0 means no collection, 1 means full collection. Default is 1. |
| enableLinkRumData | boolean | No | Whether to associate with RUM data. |
| enableCustomLog | boolean | No | Whether to enable custom logs. |
| logLevelFilters | Array |
No | Log level filtering. |
| globalContext | NSDictionary | No | Adds custom tags for logs. Refer to the rules for adding here. |
| logCacheLimitCount | number | No | Local cache maximum log entry count limit [1000,). A larger log means greater disk cache pressure. Default is 5000. |
| discardStrategy | enum FTLogCacheDiscard | No | Sets the log discard rule after reaching the limit. Default is FTLogCacheDiscard.discard. discard discards appended data, discardOldest discards old data. |
Trace Configuration¶
let traceConfig: FTTractConfig = {
enableNativeAutoTrace: true,
};
await FTReactNativeTrace.setConfig(traceConfig);
| Field | Type | Required | Description |
|---|---|---|---|
| sampleRate | number | No | Sampling rate, range [0,1]. 0 means no collection, 1 means full collection. Default is 1. |
| traceType | enum TraceType | No | Trace type. Default is TraceType.ddTrace. Options: TraceType.ddTrace, TraceType.zipkinMulti, TraceType.zipkinSingle, TraceType.traceparent, TraceType.skywalking,TraceType.jaeger. |
| enableLinkRUMData | boolean | No | Whether to associate with RUM data. Default is false. |
| enableNativeAutoTrace | boolean | No | Whether to enable native network auto-tracing for iOS NSURLSession and Android OKhttp (Since React Native network requests are implemented using system APIs on iOS and Android, enabling enableNativeAutoTrace allows all React Native data to be traced together.) |
Note:
- Please complete the SDK initialization in your top-level
index.jsfile before registering the App to ensure the SDK is fully ready before calling any other SDK methods.- Complete the basic configuration before configuring RUM, Log, and Trace.
RUM User Data Tracking¶
View¶
Native View auto-collection can be enabled by configuring enableNativeUserView in the SDK initialization RUM Configuration. React Native View is only supported for manual collection by default because React Native provides a wide range of libraries for screen navigation. You can use the following methods to manually start and stop views.
Custom View¶
Usage¶
/**
* View loading duration.
* @param viewName view name
* @param loadTime view loading duration
* @returns a Promise.
*/
onCreateView(viewName:string,loadTime:number): Promise<void>;
/**
* Start a view.
* @param viewName interface name
* @param property event context (optional)
* @returns a Promise.
*/
startView(viewName: string, property?: object): Promise<void>;
/**
* Stop a view.
* @param property event context (optional)
* @returns a Promise.
*/
stopView(property?:object): Promise<void>;
Example¶
import {FTReactNativeRUM} from '@cloudcare/react-native-mobile';
FTReactNativeRUM.onCreateView('viewName', duration);
FTReactNativeRUM.startView(
'viewName',
{ 'custom.foo': 'something' },
);
FTReactNativeRUM.stopView(
{ 'custom.foo': 'something' },
);
Auto-collect React Native View¶
If you use react-native-navigation, react-navigation, or Expo Router navigation components in React Native, you can refer to the following methods for React Native View auto-collection:
react-native-navigation¶
Add the FTRumReactNavigationTracking.tsx file from the example to your project;
Call the FTRumReactNativeNavigationTracking.startTracking() method to start collection.
import { FTRumReactNativeNavigationTracking } from './FTRumReactNativeNavigationTracking';
function startReactNativeNavigation() {
FTRumReactNativeNavigationTracking.startTracking();
registerScreens();//Navigation registerComponent
Navigation.events().registerAppLaunchedListener( async () => {
await Navigation.setRoot({
root: {
stack: {
children: [
{ component: { name: 'Home' } },
],
},
},
});
});
}
react-navigation¶
Add the FTRumReactNavigationTracking.tsx file from the example to your project;
- Method 1:
If you use createNativeStackNavigator(); to create a native navigation stack, it is recommended to use the screenListeners method to enable collection. This allows the collection of page loading duration. Specific usage is as follows:
import {FTRumReactNavigationTracking} from './FTRumReactNavigationTracking';
import { createNativeStackNavigator } from '@react-navigation/native-stack';
const Stack = createNativeStackNavigator();
<Stack.Navigator screenListeners={FTRumReactNavigationTracking.StackListener} initialRouteName='Home'>
<Stack.Screen name='Home' component={Home} options={{ headerShown: false }} />
......
<Stack.Screen name="Mine" component={Mine} options={{ title: 'Mine' }}/>
</Stack.Navigator>
- Method 2:
If you are not using createNativeStackNavigator();, you need to add the auto-collection method in the NavigationContainer component, as follows:
Note: This method cannot collect page loading duration.
import {FTRumReactNavigationTracking} from './FTRumReactNavigationTracking';
import type { NavigationContainerRef } from '@react-navigation/native';
const navigationRef: React.RefObject<NavigationContainerRef<ReactNavigation.RootParamList>> = React.createRef();
<NavigationContainer ref={navigationRef} onReady={() => {
FTRumReactNavigationTracking.startTrackingViews(navigationRef.current);
}}>
<Stack.Navigator initialRouteName='Home'>
<Stack.Screen name='Home' component={Home} options={{ headerShown: false }} />
.....
<Stack.Screen name="Mine" component={Mine} options={{ title: 'Mine' }}/>
</Stack.Navigator>
</NavigationContainer>
Refer to the example for specific usage examples.
Expo Router¶
If you are using Expo Router, add the following method in the app/_layout.js file for data collection.
import { useEffect } from 'react';
import { useSegments,usePathname, Slot } from 'expo-router';
import {
FTReactNativeRUM,
} from '@cloudcare/react-native-mobile';
export default function Layout() {
const pathname = usePathname();
const segments = useSegments();
const viewKey = segments.join('/');
useEffect(() => {
FTReactNativeRUM.startView(viewKey);
}, [viewKey, pathname]);
// Export all the children routes in the most basic way.
return <Slot />;
}
Action¶
Auto-collection can be enabled by configuring enableAutoTrackUserAction and enableNativeUserAction during SDK initialization RUM Configuration. It can also be added manually using the methods below.
Usage¶
/**
* Start a RUM Action. RUM will associate Resource, Error, LongTask events that this Action might trigger.
* Avoid adding multiple times within 0.1 s. Only one Action can be associated with the same View at the same time. If the previous Action has not ended,
* the new Action will be discarded. Does not interfere with Actions added by the `addAction` method.
* @param actionName action name
* @param actionType action type
* @param property event context (optional)
* @returns a Promise.
*/
startAction(actionName:string,actionType:string,property?:object): Promise<void>;
/**
* Add an Action event. This type of data cannot associate Error, Resource, LongTask data and has no discard logic.
* @param actionName action name
* @param actionType action type
* @param property event context (optional)
* @returns a Promise.
*/
addAction(actionName:string,actionType:string,property?:object): Promise<void>;
Code Example¶
import {FTReactNativeRUM} from '@cloudcare/react-native-mobile';
FTReactNativeRUM.startAction('actionName','actionType',{'custom.foo': 'something'});
FTReactNativeRUM.addAction('actionName','actionType',{'custom.foo': 'something'});
More Custom Collection Operations
After enabling enableAutoTrackUserAction, the SDK automatically collects click operations on components with the onPress property. If you wish to perform some custom operations on top of auto-tracking, the SDK supports the following operations:
- Customize the
actionNamefor a component's click event.
Set via the accessibilityLabel property.
<Button title="Custom Action Name"
accessibilityLabel="custom_action_name"
onPress={()=>{
console.log("btn click")
}}
/>
- Do not collect click events for a specific component.
Can be set by adding the custom parameter ft-enable-track with the value false.
- Add extra properties to a component's click event.
Can be set by adding the custom parameter ft-extra-property. The value must be a JSON string.
<Button title="Action Add Extra Properties"
ft-extra-property='{"e_name": "John Doe", "e_age": 30, "e_city": "New York"}'
onPress={()=>{
console.log("btn click")
}}
/>
Error¶
Auto-collection can be enabled by configuring enableAutoTrackError during SDK initialization RUM Configuration. It can also be added manually using the methods below.
Usage¶
/**
* Exception capture and log collection.
* @param stack stack log
* @param message error message
* @param property event context (optional)
* @returns a Promise.
*/
addError(stack: string, message: string,property?:object): Promise<void>;
/**
* Exception capture and log collection.
* @param type error type
* @param stack stack log
* @param message error message
* @param property event context (optional)
* @returns a Promise.
*/
addErrorWithType(type:string,stack: string, message: string,property?:object): Promise<void>;
Example¶
import {FTReactNativeRUM} from '@cloudcare/react-native-mobile';
FTReactNativeRUM.addError("error stack","error message",{'custom.foo': 'something'});
FTReactNativeRUM.addErrorWithType("custom_error", "error stack", "error message",{'custom.foo': 'something'});
Resource¶
Auto-collection can be enabled by configuring enableNativeUserResource during SDK initialization RUM Configuration. It can also be added manually using the methods below.
Usage¶
/**
* Start a resource request.
* @param key unique id
* @param property event context (optional)
* @returns a Promise.
*/
startResource(key: string,property?:object): Promise<void>;
/**
* Stop a resource request.
* @param key unique id
* @param property event context (optional)
* @returns a Promise.
*/
stopResource(key: string,property?:object): Promise<void>;
/**
* Send resource data metrics.
* @param key unique id
* @param resource resource data
* @param metrics resource performance data
* @returns a Promise.
*/
addResource(key:string, resource:FTRUMResource,metrics?:FTRUMResourceMetrics):Promise<void>;
Example¶
import {FTReactNativeRUM} from '@cloudcare/react-native-mobile';
async getHttp(url:string){
const key = Utils.getUUID();
FTReactNativeRUM.startResource(key);
const fetchOptions = {
method: 'GET',
headers:{
'Accept': 'application/json',
'Content-Type': 'application/json'
} ,
};
var res : Response;
try{
res = await fetch(url, fetchOptions);
}finally{
var resource:FTRUMResource = {
url:url,
httpMethod:fetchOptions.method,
requestHeader:fetchOptions.headers,
};
if (res) {
resource.responseHeader = res.headers;
resource.resourceStatus = res.status;
resource.responseBody = await res.text();
}
FTReactNativeRUM.stopResource(key);
FTReactNativeRUM.addResource(key,resource);
}
}
Logger Logging¶
The log content is currently limited to 30 KB. Characters exceeding this limit will be truncated.
Usage¶
/**
* Output a log.
* @param content log content
* @param status log status
* @param property log context (optional)
*/
logging(content:String,logStatus:FTLogStatus|String,property?:object): Promise<void>;
Example¶
import { FTReactNativeLog, FTLogStatus } from '@cloudcare/react-native-mobile';
// logStatus:FTLogStatus
FTReactNativeLog.logging("info log content",FTLogStatus.info);
// logStatus:string
FTReactNativeLog.logging("info log content","info");
Log Levels¶
| Method Name | Meaning |
|---|---|
| FTLogStatus.info | Info |
| FTLogStatus.warning | Warning |
| FTLogStatus.error | Error |
| FTLogStatus.critical | Critical |
| FTLogStatus.ok | OK / Restore |
Tracer Network Tracing¶
Auto network tracing can be enabled during SDK initialization Trace Configuration. Custom collection is also supported. The usage and examples for custom collection are as follows:
Usage¶
/**
* Get trace HTTP request header data.
* @param url request address
* @returns trace request header parameters to be added
* @deprecated use getTraceHeaderFields() replace.
*/
getTraceHeader(key:String, url: String): Promise<object>;
/**
* Get trace HTTP request header data.
* @param url request address
* @returns trace request header parameters to be added
*/
getTraceHeaderFields(url: String,key?:String): Promise<object>;
Example¶
import {FTReactNativeTrace} from '@cloudcare/react-native-mobile';
async getHttp(url:string){
const key = Utils.getUUID();
var traceHeader = await FTReactNativeTrace.getTraceHeaderFields(url);
const fetchOptions = {
method: 'GET',
headers:Object.assign({
'Accept': 'application/json',
'Content-Type': 'application/json'
},traceHeader) ,
};
try{
fetch(url, fetchOptions);
}
}
User Information Binding and Unbinding¶
Usage¶
/**
* Bind a user.
* @param userId User ID.
* @param userName User name.
* @param userEmail User email
* @param extra User's extra information
* @returns a Promise.
*/
bindRUMUserData(userId: string,userName?:string,userEmail?:string,extra?:object): Promise<void>;
/**
* Unbind a user.
* @returns a Promise.
*/
unbindRUMUserData(): Promise<void>;
Example¶
import {FTMobileReactNative} from '@cloudcare/react-native-mobile';
/**
* Bind a user.
* @param userId User ID.
* @param userName User name.
* @param userEmail User email
* @param extra User's extra information
* @returns a Promise.
*/
FTMobileReactNative.bindRUMUserData('react-native-user','uesr_name')
/**
* Unbind a user.
* @returns a Promise.
*/
FTMobileReactNative.unbindRUMUserData()
Shut Down SDK¶
Use FTMobileReactNative to shut down the SDK.
Usage¶
Example¶
Clear SDK Cache Data¶
Use FTMobileReactNative to clear cached data that has not been uploaded.
Usage¶
Example¶
/**
* Clear all data that has not yet been uploaded to the server.
*/
FTMobileReactNative.clearAllData();
Active Data Sync¶
When FTMobileConfig.autoSync is configured as true, no additional operation is needed; the SDK will sync automatically.
When FTMobileConfig.autoSync is configured as false, the data sync method needs to be triggered actively for data synchronization.
Usage¶
/**
* Actively sync data. When `FTMobileConfig.autoSync=false` is configured, this method needs to be triggered actively for data synchronization.
* @returns a Promise.
*/
flushSyncData():Promise<void>;
Example¶
Add Custom Tags¶
Usage¶
/**
* Add custom global parameters. Affects RUM and Log data.
* @param context custom global parameters.
* @returns a Promise.
*/
appendGlobalContext(context:object):Promise<void>;
/**
* Add custom RUM global parameters. Affects RUM data.
* @param context custom RUM global parameters.
* @returns a Promise.
*/
appendRUMGlobalContext(context:object):Promise<void>;
/**
* Add custom RUM and Log global parameters. Affects Log data.
* @param context custom Log global parameters.
* @returns a Promise.
*/
appendLogGlobalContext(context:object):Promise<void>;
Example¶
FTMobileReactNative.appendGlobalContext({'global_key':'global_value'});
FTMobileReactNative.appendRUMGlobalContext({'rum_key':'rum_value'});
FTMobileReactNative.appendLogGlobalContext({'log_key':'log_value'});
Symbol File Upload¶
Auto Package Symbol Files¶
Add Symbol File Auto Packaging Script¶
Script tool: react-native-mobile-cli
react-native-mobile-cli is a script tool that helps configure automatic acquisition of React Native and Native sourcemaps during release builds and packages them into zip files.
Add it to the package.json devDependencies using the local file method.
For example: Place ft-react-native-mobile-cli.tgz in the React Native project directory.
"devDependencies": {
"@cloudcare/react-native-mobile-cli":"file:./ft-react-native-mobile-cli-v1.0.0.tgz",
}
After adding, execute yarn install.
Note: The Android environment requires adding the Gradle Plugin ft-plugin, version requirement: >=1.3.4
Add the Plugin usage and parameter settings in the build.gradle file of the main module app.
apply plugin: 'ft-plugin'
FTExt {
//showLog = true
autoUploadMap = true
autoUploadNativeDebugSymbol = true
generateSourceMapOnly = true
}
Execute Configuration Command¶
Execute the command yarn ft-cli setup in the terminal under the React Native project directory. This enables automatic acquisition of React Native and Native sourcemaps during release builds and packages them into zip files. A log like the following indicates success.
➜ example git:(test-cli) ✗ yarn ft-cli setup
yarn run v1.22.22
$ /Users/xxx/example/node_modules/.bin/ft-cli setup
Starting command: Setup to automatically get react-native and native sourcemap in release build and package them as zip files.
Running task: Add a Gradle Script to automatically zip js sourcemap and Android symbols
Running task: Enable react-native sourcemap generation on iOS
Running task: Setup a new build phase in XCode to automatically zip dSYMs files and js sourcemap
Finished running command Setup to automatically get react-native and native sourcemap in release build and package them as zip files.
✅ Successfully executed: Add a Gradle Script to automatically zip js sourcemap and Android symbols.
✅ Successfully executed: Enable react-native sourcemap generation on iOS.
✅ Successfully executed: Setup a new build phase in XCode to automatically zip dSYMs files and js sourcemap.
✨ Done in 1.00s.
Location of packaged zip files after release build:
iOS: In the iOS folder (./ios/sourcemap.zip)
Android: In the RN project directory (./sourcemap.zip)
Manual Packaging of Symbol Files¶
React Native Zip Package Instructions
Upload¶
WebView Data Monitoring¶
For WebView data monitoring, the Web Monitoring SDK needs to be integrated into the WebView access page.
Data Masking¶
If you want to fully mask a field, it is recommended to use FTMobileConfig.dataModifier, which performs better. For detailed rule replacement, FTMobileConfig.lineDataModifier is recommended.
Single Field Modification (dataModifier)
- Function: Modifies the value of a single field in the data.
- Parameter format:
{key: newValue} - Example:
{"device_uuid": "xxx"}will replace thedevice_uuidfield value of the target data with "xxx".
Single Data Entry Modification (lineDataModifier)
- Function: Modifies the specified field value in a certain type of data.
- Parameter format:
{measurement: {key: newValue}} - Example:
{"view": {"view_url": "xxx"}}will modify theview_urlfield value of allviewtype data to "xxx". measurementdata type list:- RUM data:
view,resource,action,long_task,error - Log data:
log
- RUM data:
let config: FTMobileConfig = {
datakitUrl:Config.SERVER_URL,
debug: true,
dataModifier: {"device_uuid":"xxx"},
lineDataModifier:{"resource":{"response_header":"xxx"},
"view":{"view_url":"xxx"},
}
}
Custom Tag Usage Example¶
Compilation Configuration Method¶
- Use
react-native-configto configure multiple environments, setting the corresponding custom tag values in different environments.
let rumConfig: FTRUMConfig = {
iOSAppId: iOSAppId,
androidAppId: androidAppId,
monitorType: MonitorType.all,
enableTrackUserAction:true,
enableTrackUserResource:true,
enableTrackError:true,
enableNativeUserAction: false,
enableNativeUserResource: false,
enableNativeUserView: false,
globalContext:{"track_id":Config.TRACK_ID}, //Set in environment files like .env.dubug, .env.release, etc.
};
await FTReactNativeRUM.setConfig(rumConfig);
Runtime Read/Write File Method¶
- Through data persistence methods, such as
AsyncStorage, obtain the stored custom tags when initializing the SDK.
let rumConfig: FTRUMConfig = {
iOSAppId: iOSAppId,
androidAppId: androidAppId,
monitorType: MonitorType.all,
enableTrackUserAction:true,
enableTrackUserResource:true,
enableTrackError:true,
enableNativeUserAction: false,
enableNativeUserResource: false,
enableNativeUserView: false,
};
await new Promise(function(resolve) {
AsyncStorage.getItem("track_id",(error,result)=>{
if (result === null){
console.log('Failed to get' + error);
}else {
console.log('Successfully obtained' + result);
if( result != undefined){
rumConfig.globalContext = {"track_id":result};
}
}
resolve(FTReactNativeRUM.setConfig(rumConfig));
})
});
- Add or change custom tags to the file anywhere.
AsyncStorage.setItem("track_id",valueString,(error)=>{
if (error){
console.log('Storage failed' + error);
}else {
console.log('Storage successful');
}
})
- Finally, restart the application to take effect.
Add at SDK Runtime¶
After the SDK initialization is complete, use FTReactNativeRUM.appendGlobalContext(globalContext), FTReactNativeRUM.appendRUMGlobalContext(globalContext), FTReactNativeRUM.appendLogGlobalContext(globalContext) to dynamically add tags. After setting, it takes effect immediately. Subsequently, RUM or Log data reported later will automatically include the tag data. This usage is suitable for scenarios where data is obtained with delay, such as when tag data needs to be obtained through network requests.
//SDK initialization pseudo code, get
FTMobileReactNative.sdkConfig(config);
function getInfoFromNet(info:Info){
let globalContext = {"delay_key":info.value}
FTMobileReactNative.appendGlobalContext(globalContext);
}
Native and React Native Hybrid Development¶
If your project is natively developed, with some pages or business processes implemented using React Native, the SDK installation and initialization configuration methods are as follows:
-
Installation:
After the RN SDK installation is successful, there is no need to install the Android / iOS SDK on the native side. If already installed, to prevent version conflicts, we recommend using this solution:
In the Android environment, add the following dependency settings in your android/app/build.gradle file:
You can also view the corresponding native SDK version information via// Version set by TrueWatch RN SDK implementation 'com.cloudcare.ft.mobile.sdk.tracker.agent:ft-sdk implementation 'com.cloudcare.ft.mobile.sdk.tracker.agent:ft-nativenode_modules/@cloudcare/react-native-mobile/android/build.gradleIn the iOS environment, react-native manages dependency libraries through cocoapods. Please also use cocoapods for iOS SDK installation. Add the following settings in your ios/Podfile file:
You can also view the corresponding native SDK version information vianode_modules/@cloudcare/react-native-mobile/FTMobileReactNativeSDK.podspec -
Initialization: Refer to iOS SDK Initialization Configuration and Android SDK Initialization Configuration for initialization configuration within the native project.
-
React Native Configuration:
Supported in RN SDK 0.3.11
No further initialization configuration is needed on the React Native side. If automatic collection of
React Native Errorand automatic collection ofReact Native Actionare required, use the following methods: -
Native Project Configuration:
Supported in RN SDK 0.3.11
When enabling RUM Resource auto-collection, requests for React Native symbolization calls and Expo log calls that only occur in the development environment need to be filtered out. Methods are as follows:
iOS
#import <FTMobileReactNativeSDK/FTReactNativeUtils.h> #import <FTMobileSDK/FTMobileAgent.h> FTRumConfig *rumConfig = [[FTRumConfig alloc]initWithAppid:rumAppId]; rumConfig.enableTraceUserResource = YES; #if DEBUG rumConfig.resourceUrlHandler = ^BOOL(NSURL * _Nonnull url) { return [FTReactNativeUtils.filterBlackResource:url]; }; #endifAndroid
import com.ft.sdk.reactnative.utils.ReactNativeUtils; import com.ft.sdk.FTRUMConfig; FTRUMConfig rumConfig = new FTRUMConfig().setRumAppId(rumAppId); rumConfig.setEnableTraceUserResource(true); if (BuildConfig.DEBUG) { rumConfig.setResourceUrlHandler(new FTInTakeUrlHandler() { @Override public boolean isInTakeUrl(String url) { return ReactNativeUtils.isReactNativeDevUrl(url); } }); }```kotlin import com.ft.sdk.reactnative.utils.ReactNativeUtils import com.ft.sdk.FTRUMConfig
val rumConfig = FTRUMConfig().setRumAppId(rumAppId) rumConfig.isEnableTraceUserResource = true if (BuildConfig.DEBUG) { rumConfig.setResourceUrlHandler { url -> return@setResourceUrlHandler ReactNativeUtils.isReactNativeDevUrl(url) } }
```
Refer to the example for specific usage examples.
Android Resource Collection Manual Configuration¶
If encountering low-version environments or other SDK conflicts, manual Android Resource data tracking is required.
OkHttpClient client = OkHttpClientProvider.createClientBuilder()
.addInterceptor(new FTResourceInterceptor())
.addInterceptor(new FTTraceInterceptor())
.eventListenerFactory(new FTResourceEventListener.FTFactory())
.build();
//Set the OkHttpClient for React Native network requests
OkHttpClientProvider.setOkHttpClientFactory(new OkHttpClientFactory() {
@Override
public OkHttpClient createNewNetworkModuleClient() {
return client;
}
});
val client = OkHttpClientProvider.createClientBuilder()
.addInterceptor(FTResourceInterceptor())
.addInterceptor(FTTraceInterceptor())
.eventListenerFactory(FTResourceEventListener.FTFactory())
.build()
// Set the OkHttpClient for React Native network requests
OkHttpClientProvider.setOkHttpClientFactory(object : OkHttpClientFactory {
override fun createNewNetworkModuleClient(): OkHttpClient {
return client
}
})