React Native Application Integration¶
Prerequisites¶
Note
If the RUM Headless service has been activated, prerequisites have been automatically configured, and you can directly integrate the application.
- Install DataKit;
- Configure RUM Collector;
- Configure DataKit for public network access and install IP geolocation database.
Application Integration¶
Note
The current React Native version only supports Android and iOS platforms.
- Enter User Analysis > Create > React Native;
- Input application name;
- Input application ID;
-
Select application integration method:
- Public DataWay: Directly receives RUM data without installing DataKit collector.
- Local Environment Deployment: Receives RUM data after meeting the prerequisites.
Installation¶
Source code address: https://github.com/GuanceCloud/datakit-react-native
Demo address: https://github.com/GuanceCloud/datakit-react-native/example
In the project path, run the command in the terminal:
This will add the following line to your package.json file:
Additional Configuration for Android Integration:
- Configure Gradle Plugin ft-plugin to collect App startup events and network request data, as well as Android Native related events (page transitions, click events, Native network requests, WebView data).
- Note that you need to configure the Guance Android Maven repository address simultaneously in Gradle for both Plugin and AAR. Refer to the configuration details in the example 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 | Local environment deployment (Datakit) reporting URL address, example: http://10.0.0.1:9529, default port 9529, the device with the installed SDK needs to be able to access this address. Note: Choose one between datakitUrl and datawayUrl |
datawayUrl | string | Yes | Public Dataway reporting URL address, obtained from [User Analysis] application, example: https://open.dataway.url, the device with the installed SDK needs to be able to access this address. Note: Choose one between datakitUrl and datawayUrl |
clientToken | string | Yes | Authentication token, must be used together with datawayUrl |
debug | boolean | No | Set whether to allow log printing, default false |
env | string | No | Environment configuration, default prod , any character, it is recommended to use a single word, such as test etc. |
envType | enum EnvType | No | Environment configuration, default EnvType.prod . Note: Only one of env or envType needs to be configured |
service | string | No | Set the name of the associated business or service, affects the service field data in Log and RUM. Default: df_rum_ios , df_rum_android |
autoSync | boolean | No | Whether to automatically synchronize data to the server after collection, default true . When set to false , use FTMobileReactNative.flushSyncData() to manage data synchronization yourself |
syncPageSize | number | No | Set the number of entries per sync request. Range [5,). Note: The larger the number of request entries, the more computational resources are used for data synchronization |
syncSleepTime | number | No | Set the intermittent sync time. Range [0,5000], default not set |
enableDataIntegerCompatible | boolean | No | It is recommended to enable this when coexisting with web data. This configuration handles compatibility issues with web data types storage. Automatically enabled in versions 0.3.12 and later |
globalContext | object | No | Add custom tags. Refer to here for addition rules |
compressIntakeRequests | boolean | No | Compress uploaded sync data using deflate compression, default off |
enableLimitWithDbSize | boolean | No | Enable using db size limit, default 100MB, unit Byte, larger databases increase disk pressure, default off. Note: After enabling, the logCacheLimitCount setting in Log configuration and the rumCacheLimitCount setting in RUM configuration will become ineffective. Supported in SDK versions 0.3.10 and above |
dbCacheLimit | number | No | DB cache size limit. Range [30MB,), default 100MB, unit byte, supported in SDK versions 0.3.10 and above |
dbDiscardStrategy | string | No | Set the data discard rule in the database. Discard strategy: FTDBCacheDiscard.discard discards new data (default), FTDBCacheDiscard.discardOldest discards old data. Supported in SDK versions 0.3.10 and above |
dataModifier | object | No | Modify individual fields. Supported in SDK versions 0.3.14 and above, refer to here for usage examples |
lineDataModifier | object | No | Modify individual data entries. Supported in SDK versions 0.3.14 and above, refer to here for usage examples |
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 through the User Analysis console |
iOSAppId | string | Yes | app_id, applied through the User Analysis console |
sampleRate | number | No | Sampling rate, range [0,1], 0 means no collection, 1 means full collection, default value is 1. Scope applies to all View, Action, LongTask, Error data under the same session_id |
sessionOnErrorSampleRate | number | No | Set error sampling rate, if the session is not sampled by sampleRate , data within the last minute before the error occurs during the session can still be collected, range [0,1], 0 means no collection, 1 means full collection, default value is 0. Scope applies to all View, Action, LongTask, Error data under the same session_id. Supported in SDK versions 0.3.14 and above |
enableAutoTrackUserAction | boolean | No | Whether to automatically collect React Native component click events, can be combined with accessibilityLabel to set actionName, refer to here for more customization |
enableAutoTrackError | boolean | No | Whether to automatically collect React Native Errors, default false |
enableNativeUserAction | boolean | No | Whether to track Native Action , native Button click events, app startup events, default false |
enableNativeUserView | boolean | No | Whether to perform Native View automatic tracking, pure React Native applications are recommended to turn this off, default false |
enableNativeUserResource | boolean | No | Whether to start Native Resource automatic tracking, since React-Native network requests on iOS and Android use system APIs, enabling enableNativeUserResource will collect all resource data. Default false |
errorMonitorType | enum ErrorMonitorType | No | Set auxiliary monitoring information, add additional monitoring data to RUM Error data, ErrorMonitorType.battery for battery level, ErrorMonitorType.memory for memory usage, ErrorMonitorType.cpu for CPU usage, default not enabled |
deviceMonitorType | enum DeviceMetricsMonitorType | No | In the View lifecycle, add monitoring data, DeviceMetricsMonitorType.battery (Android only) monitors the maximum output current on the current page, DeviceMetricsMonitorType.memory monitors the current application memory usage, DeviceMetricsMonitorType.cpu monitors CPU jumps, DeviceMetricsMonitorType.fps monitors screen frame rate, default not enabled |
detectFrequency | enum DetectFrequency | No | Sampling cycle for view performance monitoring, default DetectFrequency.normal |
enableResourceHostIP | boolean | No | Whether to collect the IP address of the target domain. Scope: Only affects default collection when enableNativeUserResource is true . iOS: Supported on >= iOS 13 . Android: Okhttp caches IP for the same domain, for the same OkhttpClient , it generates only once unless the connected server IP changes. |
globalContext | object | No | Add custom tags for user monitoring data source distinction. If tracking function is required, parameter key should be track_id , value can be any number. Refer to here for notes on adding rules |
enableTrackNativeCrash | boolean | No | Whether to enable Android Java Crash and OC/C/C++ crash monitoring, default false |
enableTrackNativeAppANR | boolean | No | Whether to enable Native ANR monitoring, default false |
enableTrackNativeFreeze | boolean | No | Whether to collect Native Freeze , default false |
nativeFreezeDurationMs | number | No | Set 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 | Maximum number of cached RUM entries locally [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 value is 1. |
enableLinkRumData | boolean | No | Whether to link with RUM |
enableCustomLog | boolean | No | Whether to enable custom logs |
logLevelFilters | Array |
No | Log level filter |
globalContext | NSDictionary | No | Add custom log tags, refer to here for addition rules |
logCacheLimitCount | number | No | Maximum number of locally cached log entries [1000,), larger logs mean greater disk cache pressure, default 5000 |
discardStrategy | enum FTLogCacheDiscard | No | Set the log discard rule when reaching the limit. Default 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 value is 1. |
traceType | enum TraceType | No | Trace type, default TraceType.ddTrace |
enableLinkRUMData | boolean | No | Whether to link with RUM data, default false |
enableNativeAutoTrace | boolean | No | Whether to enable native network automatic tracing for iOS NSURLSession, Android OKhttp (Since React Native network requests on iOS and Android use system APIs, enabling enableNativeAutoTrace allows all React Native data to be traced.) |
Note:
- Ensure that the SDK is initialized before registering the App in your top-level
index.js
file to ensure the SDK is fully ready before calling any other SDK methods.- Complete basic configuration before configuring RUM, Log, and Trace.
RUM User Data Tracking¶
View¶
When initializing the SDK RUM Configuration, you can configure enableNativeUserView
to enable automatic collection of Native Views
, React Native Views
due to React Native providing extensive libraries for creating screen navigation, so by default, manual collection is supported. You can manually start and stop views using the following methods.
Custom View¶
Usage Method¶
/**
* View loading duration.
* @param viewName view name
* @param loadTime view loading duration
* @returns a Promise.
*/
onCreateView(viewName:string,loadTime:number): Promise<void>;
/**
* View start.
* @param viewName interface name
* @param property event context (optional)
* @returns a Promise.
*/
startView(viewName: string, property?: object): Promise<void>;
/**
* View end.
* @param property event context (optional)
* @returns a Promise.
*/
stopView(property?:object): Promise<void>;
Usage Example¶
import {FTReactNativeRUM} from '@cloudcare/react-native-mobile';
FTReactNativeRUM.onCreateView('viewName', duration);
FTReactNativeRUM.startView(
'viewName',
{ 'custom.foo': 'something' },
);
FTReactNativeRUM.stopView(
{ 'custom.foo': 'something' },
);
Automatic Collection of React Native Views¶
If you use react-native-navigation
, react-navigation
, or Expo Router
navigation components in React Native, you can refer to the following methods for automatic collection of React Native Views
:
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 One:
If you use createNativeStackNavigator();
to create a native navigation stack, it is recommended to use the screenListeners
approach to enable collection, which can measure the page loading duration, as shown below:
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 Two:
If you do not use createNativeStackNavigator();
, you need to add an automatic 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 use Expo Router, add the following method in the app/_layout.js file for data collection.
import { useEffect } from 'react';
import { useSegments, Slot } from 'expo-router';
import {
FTReactNativeRUM,
} from '@cloudcare/react-native-mobile';
export default function Layout() {
const segments = useSegments();
const viewKey = segments.join('/');
useEffect(() => {
FTReactNativeRUM.startView(viewKey);
}, [viewKey, pathname]);
// Export all the child routes in the most basic way.
return <Slot />;
}
Action¶
When initializing the SDK RUM Configuration, configure enableAutoTrackUserAction
and enableNativeUserAction
to enable automatic collection, or manually add via the following methods.
Usage Method¶
/**
* Start RUM Action. RUM will bind this Action to possible triggered Resource, Error, LongTask events.
* Avoid multiple additions within 0.1 seconds. Only one Action can be associated with the same View at the same time, and if the previous Action has not ended,
* the new Action will be discarded. Adding Actions using `addAction` method does not affect each other.
* @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 Action event. Such data cannot be associated with Error, Resource, LongTask data, and there is 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 Customized Collection Operations
After enabling enableAutoTrackUserAction
, the SDK will automatically collect click operations for components with the onPress
attribute. If you wish to execute some customized operations on top of automatic tracking, the SDK supports the following:
- Customize the
actionName
for a component's click event
Set using the accessibilityLabel
attribute
<Button title="Custom Action Name"
accessibilityLabel="custom_action_name"
onPress={()=>{
console.log("btn click")
}}
/>
- Do not collect click events for a certain component
Can be set by adding the ft-enable-track
custom parameter, set to false
- Add extra attributes to a component's click event
Can be set by adding the ft-extra-property
custom parameter, requiring Json string value
<Button title="Action 添加额外属性"
ft-extra-property='{"e_name": "John Doe", "e_age": 30, "e_city": "New York"}'
onPress={()=>{
console.log("btn click")
}}
/>
Error¶
When initializing the SDK RUM Configuration, configure enableAutoTrackError
to enable automatic collection, or manually add via the following methods.
Usage Method¶
/**
* 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>;
Usage 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¶
When initializing the SDK RUM Configuration, configure enableNativeUserResource
to enable automatic collection, or manually add via the following methods.
Usage Method¶
/**
* Start resource request.
* @param key unique id
* @param property event context (optional)
* @returns a Promise.
*/
startResource(key: string,property?:object): Promise<void>;
/**
* End 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>;
Usage 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¶
Currently, log content is limited to 30 KB, exceeding characters will be truncated.
Usage Method¶
/**
* Output log.
* @param content log content
* @param status log status
* @param property log context (optional)
*/
logging(content:String,logStatus:FTLogStatus|String,property?:object): Promise<void>;
Usage 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 | Information |
FTLogStatus.warning | Warning |
FTLogStatus.error | Error |
FTLogStatus.critical | Critical |
FTLogStatus.ok | Recovery |
Tracer Network Trace¶
When initializing the SDK Trace Configuration, you can enable automatic network trace, or support user-defined collection. The usage method and examples for user-defined collection are as follows:
Usage Method¶
/**
* Get trace http request header data.
* @param url Request address
* @returns trace added request header parameters
* @deprecated use getTraceHeaderFields() replace.
*/
getTraceHeader(key:String, url: String): Promise<object>;
/**
* Get trace http request header data.
* @param url Request address
* @returns trace added request header parameters
*/
getTraceHeaderFields(url: String,key?:String): Promise<object>;
Usage 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 Method¶
/**
* Bind user.
* @param userId User ID.
* @param userName User name.
* @param userEmail User email
* @param extra Additional user information
* @returns a Promise.
*/
bindRUMUserData(userId: string,userName?:string,userEmail?:string,extra?:object): Promise<void>;
/**
* Unbind user.
* @returns a Promise.
*/
unbindRUMUserData(): Promise<void>;
Usage Example¶
import {FTMobileReactNative} from '@cloudcare/react-native-mobile';
/**
* Bind user.
* @param userId User ID.
* @param userName User name.
* @param userEmail User email
* @param extra Additional user information
* @returns a Promise.
*/
FTMobileReactNative.bindRUMUserData('react-native-user','uesr_name')
/**
* Unbind user.
* @returns a Promise.
*/
FTMobileReactNative.unbindRUMUserData()
Closing the SDK¶
Use FTMobileReactNative
to close the SDK.
Usage Method¶
Usage Example¶
Clearing SDK Cache Data¶
Use FTMobileReactNative
to clear unsent cache data.
Usage Method¶
Usage Example¶
Active Data Synchronization¶
When FTMobileConfig.autoSync
is set to true
, no additional actions are required, the SDK will automatically synchronize data.
When FTMobileConfig.autoSync
is set to false
, you need to trigger the data synchronization method manually to synchronize data.
Usage Method¶
/**
* Actively synchronize data, when `FTMobileConfig.autoSync=false`, you need to trigger this method manually to synchronize data.
* @returns a Promise.
*/
flushSyncData():Promise<void>;
Usage Example¶
Adding Custom Tags¶
Usage Method¶
/**
* Add custom global parameters. Applies to RUM, Log data.
* @param context Custom global parameters.
* @returns a Promise.
*/
appendGlobalContext(context:object):Promise<void>;
/**
* Add custom RUM global parameters. Applies to RUM data.
* @param context Custom RUM global parameters.
* @returns a Promise.
*/
appendRUMGlobalContext(context:object):Promise<void>;
/**
* Add custom RUM, Log global parameters. Applies to Log data.
* @param context Custom Log global parameters.
* @returns a Promise.
*/
appendLogGlobalContext(context:object):Promise<void>;
Usage Example¶
FTMobileReactNative.appendGlobalContext({'global_key':'global_value'});
FTMobileReactNative.appendRUMGlobalContext({'rum_key':'rum_value'});
FTMobileReactNative.appendLogGlobalContext({'log_key':'log_value'});
Symbol File Upload¶
Automatic Packing of Symbol Files¶
Add Script for Automatic Packing of Symbol Files¶
Script tool: cloudcare-react-native-mobile-cli
cloudcare-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.
Use the local file method to add it to the package.json
development dependencies.
For example: Place cloudcare-react-native-mobile-cli.tgz
in the React Native project directory.
"devDependencies": {
"@cloudcare/react-native-mobile-cli":"file:./cloudcare-react-native-mobile-cli-v1.0.0.tgz",
}
Run yarn install
after adding.
Note: Android environments require adding Gradle Plugin ft-plugin, version requirement: >=1.3.4
Add Plugin
usage and parameter settings in the main module app
's build.gradle
file.
apply plugin: 'ft-plugin'
FTExt {
//showLog = true
autoUploadMap = true
autoUploadNativeDebugSymbol = true
generateSourceMapOnly = true
}
Execute Configuration Command¶
Execute the yarn ft-cli setup
command in the React Native project directory to automatically acquire React Native and Native sourcemaps during release builds and package them into zip files. If the following logs appear, it indicates successful setup.
➜ 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.
Release build zip file location after packaging:
iOS: iOS folder (./ios/sourcemap.zip)
Android: RN project directory (./sourcemap.zip)
Manual Packing of Symbol Files¶
React Native Zip Package Packing Instructions
Upload¶
WebView Data Monitoring¶
To monitor WebView data, integrate the Web Monitoring SDK in the pages accessed by WebView.
Data Masking¶
If you want to fully mask a field, it is recommended to use FTMobileConfig.dataModifier
for better performance. If detailed rule replacement is needed, recommend using FTMobileConfig.lineDataModifier
.
Single Field Modification (dataModifier)
-
Function: Modify the value of a single field in the data
-
Parameter Format:
{key: newValue}
-
Example:
{"device_uuid": "xxx"}
will replace thedevice_uuid
field value in the target data with "xxx"
Single Data Entry Modification (lineDataModifier)
-
Function: Modify the specified field value in a certain type of data
-
Parameter Format:
{measurement: {key: newValue}}
- Example:
{"view": {"view_url": "xxx"}}
will modify theview_url
field value of allview
type data to "xxx" measurement
Data 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-config
to configure multi-environments, setting 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}, //.env.dubug、.env.release etc., environmental files where configurations are set
};
await FTReactNativeRUM.setConfig(rumConfig);
Runtime Read/Write File Method¶
- Through data persistence methods like
AsyncStorage
, obtain 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 retrieve' + error);
}else {
console.log('Retrieved successfully' + result);
if( result != undefined){
rumConfig.globalContext = {"track_id":result};
}
}
resolve(FTReactNativeRUM.setConfig(rumConfig));
})
});
- Add or change custom tags to the file at any point.
AsyncStorage.setItem("track_id",valueString,(error)=>{
if (error){
console.log('Storage failed' + error);
}else {
console.log('Stored successfully');
}
})
- Finally, restart the application for changes to take effect.
SDK Runtime Addition¶
After the SDK is initialized, use FTReactNativeRUM.appendGlobalContext(globalContext)
, FTReactNativeRUM.appendRUMGlobalContext(globalContext)
, FTReactNativeRUM.appendLogGlobalContext(globalContext)
to dynamically add tags. The settings will take effect immediately. Subsequently, RUM or Log data reported later will automatically include tag data. This method is suitable for scenarios where data needs to be delayed, such as when tag data requires network requests to obtain.
//SDK Initialization Pseudo-code, get info
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 installation and initialization configuration methods for the SDK are as follows:
-
Installation: Installation remains unchanged
-
Initialization: Refer to iOS SDK Initialization Configuration, Android SDK Initialization Configuration for native project initialization configuration
-
React Native Configuration:
RN SDK 0.3.11 supports
In the React Native side, there is no need for initialization configuration again. If you want to automatically collect
React Native Error
and automatically collectReact Native Action
, follow the methods below: -
Native Project Configuration:
RN SDK 0.3.11 supports
When enabling RUM Resource automatic collection, it is necessary to filter out React Native symbolization calls and Expo log calls that only occur in the development environment. Method 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]; }; #endif
Android
import com.cloudcare.ft.mobile.sdk.tracker.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); } }); }
import com.cloudcare.ft.mobile.sdk.tracker.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.