React Native Application Integration¶
Prerequisites¶
Note
If the RUM Headless service has been activated, the prerequisites are automatically configured, and you can directly integrate the application.
- Install DataKit;
- Configure the RUM Collector;
- Configure DataKit to be accessible over the public network and install the IP geolocation database.
Application Integration¶
Note
The current React Native version only supports Android and iOS platforms.
- Go to User Access Monitoring > Create Application > React Native;
- Create two applications for React Native Android and React Native iOS respectively to receive RUM data from Android and iOS platforms;
- Enter the corresponding application name and application ID for each platform's application;
- Choose the application integration method:
- Public Network DataWay: Directly receives RUM data without installing the DataKit collector.
- Local Environment Deployment: Receives RUM data after meeting the prerequisites.
Installation¶
Source Code: https://github.com/GuanceCloud/datakit-react-native
Demo: https://github.com/GuanceCloud/datakit-react-native/example
In the project directory, run the following command in the terminal:
This will add the following line to the package.json:
Additional Configuration for Android Integration:
- Configure the Gradle Plugin ft-plugin to collect App startup events and network request data, as well as Android Native related events (page navigation, click events, Native network requests, WebView data).
- Note that you need to configure the Guance Android Maven repository address in Gradle. Both the Plugin and AAR are required. 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 network 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 installing the SDK must be able to access this address. Note: Choose either datakitUrl or datawayUrl |
| datawayUrl | string | Yes | Public network Dataway reporting URL address, obtained from the [User Access Monitoring] application, example: https://open.dataway.url, the device installing the SDK must be able to access this address. Note: Choose either datakitUrl or datawayUrl |
| clientToken | string | Yes | Authentication token, must be used with datawayUrl |
| debug | boolean | No | Set whether to allow log printing, default false |
| env | string | No | Environment configuration, default prod, any character, recommended to use a single word, such as test etc. |
| envType | enum EnvType | No | Environment configuration, default EnvType.prod. Note: Only one of env and envType needs to be configured |
| service | string | No | Set the name of the business or service, affecting the service field data in Log and RUM. Default: df_rum_ios, df_rum_android |
| autoSync | boolean | No | Whether to automatically sync data to the server after collection, default true. When false, use FTMobileReactNative.flushSyncData() to manage data synchronization manually |
| syncPageSize | number | No | Set the number of entries for synchronization requests. Range [5,) Note: The larger the number of entries, the more computational resources the data synchronization occupies |
| syncSleepTime | number | No | Set the synchronization interval time. Range [0,5000], default not set |
| enableDataIntegerCompatible | boolean | No | Recommended to enable when coexisting with web data. This configuration is used to handle web data type storage compatibility issues. Enabled by default in versions after 0.3.12 |
| globalContext | object | No | Add custom tags. Add rules refer to here |
| compressIntakeRequests | boolean | No | Deflate compression for upload synchronization data, default off |
| enableLimitWithDbSize | boolean | No | Enable db size limit for data, default 100MB, unit Byte, the larger the database, the greater the disk pressure, default not enabled. Note: After enabling, Log configuration logCacheLimitCount and RUM configuration rumCacheLimitCount will be invalid. Supported in SDK versions above 0.3.10 |
| dbCacheLimit | number | No | DB cache limit size. Range [30MB,), default 100MB, unit byte, supported in SDK versions above 0.3.10 |
| dbDiscardStrategy | string | No | Set the data discard rule in the database. Discard strategy: FTDBCacheDiscard.discard discard new data (default), FTDBCacheDiscard.discardOldest discard old data. Supported in SDK versions above 0.3.10 |
| dataModifier | object | No | Modify a single field. Supported in SDK versions above 0.3.14, usage example see here |
| lineDataModifier | object | No | Modify a single line of data. Supported in SDK versions above 0.3.14, usage example see 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 from the User Access Monitoring console |
| iOSAppId | string | Yes | app_id, applied from the User Access Monitoring console |
| sampleRate | number | No | Sampling rate, range [0,1], 0 means no collection, 1 means full collection, default value is 1. Scope is all View, Action, LongTask, Error data under the same session_id |
| sessionOnErrorSampleRate | number | No | Set error collection rate, when the session is not sampled by sampleRate, if an error occurs during the session, data within 1 minute before the error can be collected, range [0,1], 0 means no collection, 1 means full collection, default value is 0. Scope is all View, Action, LongTask, Error data under the same session_id. Supported in SDK versions above 0.3.14 |
| enableAutoTrackUserAction | boolean | No | Whether to automatically collect React Native component click events, after enabling, you can set actionName with accessibilityLabel, for more custom operations refer to here |
| enableAutoTrackError | boolean | No | Whether to automatically collect React Native Error, default false |
| enableNativeUserAction | boolean | No | Whether to track Native Action, native Button click events, app startup events, default false |
| enableNativeUserView | boolean | No | Whether to track Native View automatically, recommended to turn off for pure React Native applications, default false |
| enableNativeUserResource | boolean | No | Whether to start Native Resource automatic tracking, since React-Native network requests are implemented using system APIs on iOS and Android, after enabling enableNativeUserResource, all resource data can be collected together. 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 | Add monitoring data during the View cycle, DeviceMetricsMonitorType.battery (only Android) monitors the maximum output current of the current page, DeviceMetricsMonitorType.memory monitors the memory usage of the current application, DeviceMetricsMonitorType.cpu monitors CPU jumps, DeviceMetricsMonitorType.fps monitors screen frame rate, default not enabled |
| detectFrequency | enum DetectFrequency | No | View performance monitoring sampling period, default DetectFrequency.normal |
| enableResourceHostIP | boolean | No | Whether to collect the IP address of the request target domain name. Scope: only affects the default collection when enableNativeUserResource is true. iOS: supported on >= iOS 13. Android: A single Okhttp has an IP cache mechanism for the same domain name, the same OkhttpClient, under the condition that the server IP does not change, will only be generated once. |
| globalContext | object | No | Add custom tags, used to distinguish user monitoring data sources, if you need to use tracking function, the parameter key is track_id, value is any value, add rule precautions refer to here |
| 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 stutter, range [100,), unit milliseconds. iOS default 250ms, Android default 1000ms |
| rumDiscardStrategy | string | No | Discard strategy: FTRUMCacheDiscard.discard discard new data (default), FTRUMCacheDiscard.discardOldest discard old data |
| rumCacheLimitCount | number | No | Local cache maximum RUM entry 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 value is 1. |
| enableLinkRumData | boolean | No | Whether to associate with RUM |
| enableCustomLog | boolean | No | Whether to enable custom logs |
| logLevelFilters | Array |
No | Log level filter |
| globalContext | NSDictionary | No | Add log custom tags, add rules refer to here |
| logCacheLimitCount | number | No | Local cache maximum log entry limit [1000,), the larger the log, the greater the disk cache pressure, default 5000 |
| discardStrategy | enum FTLogCacheDiscard | No | Set the log discard rule when the log reaches the limit. Default FTLogCacheDiscard.discard, discard discard appended data, discardOldest discard 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. TraceType.ddTrace, TraceType.zipkinMulti, TraceType.zipkinSingle, TraceType.traceparent, TraceType.skywalking,TraceType.jaeger |
| enableLinkRUMData | boolean | No | Whether to associate with RUM data, default false |
| enableNativeAutoTrace | boolean | No | Whether to enable native network automatic tracing iOS NSURLSession ,Android OKhttp (Since React Native network requests are implemented using system APIs on iOS and Android, after enabling enableNativeAutoTrace, all React Native data can be traced together.) |
Note:
- Please complete the SDK initialization in your top-level
index.jsfile before registering the App to ensure that the SDK is fully ready before calling any other methods of the SDK.- Complete the basic configuration before configuring RUM, Log, Trace.
RUM User Data Tracking¶
View¶
In the SDK initialization RUM Configuration, you can configure enableNativeUserView to enable automatic collection of Native View. React Native View is only supported for manual collection by default since React Native provides a wide range of libraries for creating screen navigation. You can use the following methods to manually start and stop views.
Custom View¶
Usage¶
/**
* View load time.
* @param viewName view name
* @param loadTime view load time
* @returns a Promise.
*/
onCreateView(viewName:string,loadTime:number): Promise<void>;
/**
* View start.
* @param viewName view 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>;
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 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 automatic collection of React Native View:
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 start collection, so that the page load time can be counted. The 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 do not use createNativeStackNavigator();, you need to add the automatic collection method in the NavigationContainer component, as follows:
Note: This method cannot collect page load time
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>
For specific usage examples, refer to example.
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¶
In the SDK initialization RUM Configuration, configure enableAutoTrackUserAction and enableNativeUserAction to enable automatic collection, or use the following methods to add manually.
Usage¶
/**
* Start RUM Action. RUM will associate the Action with possible triggered Resource, Error, LongTask events.
* 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 newly added Action will be discarded. Does not affect the Action added by `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 Action event. This type of data cannot associate Error, Resource, LongTask data, 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>;
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 will automatically collect click operations of components with the onPress attribute. If you wish to perform some custom operations on top of automatic tracking, the SDK supports the following operations:
- Customize the
actionNameof a component's click event
Set via the accessibilityLabel attribute
<Button title="Custom Action Name"
accessibilityLabel="custom_action_name"
onPress={()=>{
console.log("btn click")
}}
/>
- Do not collect the click event of a component
Can be set by adding the ft-enable-track custom parameter, set the value to false
- Add additional attributes to a component's click event
Can be set by adding the ft-extra-property custom parameter, the value must be a Json string
<Button title="Action Add Extra Attributes"
ft-extra-property='{"e_name": "John Doe", "e_age": 30, "e_city": "New York"}'
onPress={()=>{
console.log("btn click")
}}
/>
Error¶
In the SDK initialization RUM Configuration, configure enableAutoTrackError to enable automatic collection, or use the following methods to add manually.
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¶
In the SDK initialization RUM Configuration, configure enableNativeUserResource to enable automatic collection, or use the following methods to add manually.
Usage¶
/**
* 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>;
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 Log Printing¶
Currently, the log content is limited to 30 KB, and the excess characters will be truncated.
Usage¶
/**
* 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>;
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 |
Tracer Network Trace¶
SDK initialization Trace Configuration can enable automatic network trace, and also supports user-defined collection. The usage and examples of custom collection are as follows:
Usage¶
/**
* 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>;
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 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 user.
* @returns a Promise.
*/
unbindRUMUserData(): Promise<void>;
Example¶
import {FTMobileReactNative} from '@cloudcare/react-native-mobile';
/**
* Bind 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 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 unuploaded cache data.
Usage¶
Example¶
/**
* Clear all data that has not 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 automatically sync.
When FTMobileConfig.autoSync is configured as false, you need to actively trigger the data sync method to sync data.
Usage¶
/**
* Actively sync data, when `FTMobileConfig.autoSync=false`, you need to actively trigger this method to sync data.
* @returns a Promise.
*/
flushSyncData():Promise<void>;
Example¶
Add Custom Tags¶
Usage¶
/**
* 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>;
Example¶
FTMobileReactNative.appendGlobalContext({'global_key':'global_value'});
FTMobileReactNative.appendRUMGlobalContext({'rum_key':'rum_value'});
FTMobileReactNative.appendLogGlobalContext({'log_key':'log_value'});
Symbol File Upload¶
Automatic Symbol File Packaging¶
Add Symbol File Automatic Packaging Script¶
Script tool: react-native-mobile-cli
react-native-mobile-cli is a script tool to help configure automatic acquisition of React Native and Native sourcemaps during release build and package them into zip files.
Add to the development dependencies in package.json using the local file method.
For example: When ft-react-native-mobile-cli.tgz is placed 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: For Android environment, you need to add the configuration Gradle Plugin ft-plugin, version requirement: >=1.3.4
Add the use of Plugin and parameter settings in the build.gradle file of the main module app of the project.
apply plugin: 'ft-plugin'
FTExt {
//showLog = true
autoUploadMap = true
autoUploadNativeDebugSymbol = true
generateSourceMapOnly = true
}
Execute Configuration Command¶
Execute the terminal command yarn ft-cli setup in the React Native project directory to enable automatic acquisition of React Native and Native sourcemaps during release build and package them into zip files. The following log 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.
After release build, the packaged zip file address:
iOS: iOS folder (./ios/sourcemap.zip)
Android: RN project directory (./sourcemap.zip).
Manual Symbol File Packaging¶
React Native Zip Package Packaging Instructions
Upload¶
WebView Data Monitoring¶
WebView data monitoring requires the integration of Web Monitoring SDK in the WebView access page.
Data Masking¶
If you want to fully mask a field, it is recommended to use FTMobileConfig.dataModifier, which performs better. If you need detailed rule replacement, it is recommended to use 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_uuidfield value of the target data with "xxx"
Single Line Data 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_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, and set 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}, //.env.dubug、.env.release and other configuration environment files
};
await FTReactNativeRUM.setConfig(rumConfig);
Runtime Read-Write File Method¶
- Through data persistence methods, such as
AsyncStorage, etc., when initializing the SDK, get the stored custom tags.
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('Get failed' + error);
}else {
console.log('Get success' + 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 success');
}
})
- Finally, restart the application to take effect.
SDK Runtime Add¶
After the SDK initialization is completed, use FTReactNativeRUM.appendGlobalContext(globalContext), FTReactNativeRUM.appendRUMGlobalContext(globalContext), FTReactNativeRUM.appendLogGlobalContext(globalContext) to dynamically add tags. After setting, it will take effect immediately. Subsequently, RUM or Log data reported later will automatically add tag data. This usage is suitable for scenarios where data is obtained with delay, such as 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 developed natively, and some pages or business processes are implemented using React Native, the SDK installation and initialization configuration methods are as follows:
-
Installation:
After RN SDK installation is successful, the native side does not need to install Android / iOS SDK again. If it has been installed, to prevent version conflicts, we recommend you use this solution:
In the Android environment, please add the following dependency settings in your android/app/build.gradle file:
You can also view the corresponding native SDK version information through// Version set by Guance 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. The installation of iOS SDK also uses cocoapods. Please add the following settings in your ios/Podfile file:
You can also view the corresponding native SDK version information throughnode_modules/@cloudcare/react-native-mobile/FTMobileReactNativeSDK.podspec -
Initialization: Please refer to iOS SDK Initialization Configuration and Android SDK Initialization Configuration for initialization configuration in the native project.
-
React Native Configuration:
RN SDK 0.3.11 supports
No need to initialize configuration again on the React Native side. If you need to automatically collect
React Native Errorand automatically collectReact Native Action, the methods are as follows: -
Native Project Configuration:
RN SDK 0.3.11 supports
When enabling RUM Resource automatic collection, you need to filter out React Native symbolization call requests and Expo log call requests that only occur in the development environment. The 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); } }); }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) }
For specific usage examples, refer to example.
Android Resource Collection Manual Configuration¶
If you encounter some low-version environments or other SDK conflicts, you need to manually configure Android Resource data tracking.
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
}
})
Publish Package Related Configuration¶
Android¶
iOS¶
Frequently Asked Questions¶
- Android Privacy Review
- iOS Other Related
- Android Other Related# Frequently Asked Questions
Android Privacy Review¶
For details on how to handle privacy-related issues during the Android app review process, refer to Android Privacy Review.
iOS Other Related¶
For other common issues related to iOS, refer to iOS Other Related.
Android Other Related¶
For other common issues related to Android, refer to Android Other Related.