React Native Application Integration¶
Prerequisites¶
Note
If you have already activated the RUM Headless service, 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 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 TrueWatch Android Maven repository address in Gradle, both for the Plugin and AAR. For configuration details, refer to the build.gradle in the example.
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,
};
//Using 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, port defaults to 9529, the device installing the SDK must be able to access this address. Note: Choose either datakitUrl or datawayUrl configuration |
datawayUrl | string | Yes | Public 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 configuration |
clientToken | string | Yes | Authentication token, must be used with datawayUrl |
debug | boolean | No | Set whether to allow logging, 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 or envType needs to be configured |
service | string | No | Set the name of the 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 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 request entries, the more computational resources the data synchronization will occupy |
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. Default enabled after version 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 using db to limit data size, 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 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 | Set the data discard rule in the database. Discard strategy: FTDBCacheDiscard.discard discard new data (default), FTDBCacheDiscard.discardOldest discard old data. Supported in SDK version 0.3.10 and above |
dataModifier | object | No | Modify a single field. Supported in SDK version 0.3.14 and above, usage example see here |
lineDataModifier | object | No | Modify a single piece of data. Supported in SDK version 0.3.14 and above, 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 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 from the 1 minute before the error can be collected, range [0,1], 0 means no collection, 1 means full collection, default is 0. Scope is 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, 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 automatically track Native View , 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 | In the View cycle, add monitoring data, DeviceMetricsMonitorType.battery (only Android) monitor the maximum output current of the current page, DeviceMetricsMonitorType.memory monitor the current application memory usage, DeviceMetricsMonitorType.cpu monitor CPU jumps, DeviceMetricsMonitorType.fps monitor 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: >= iOS 13 supported. Android: Single Okhttp has an IP caching mechanism for the same domain name, the same OkhttpClient , under the condition that the server IP does not change, will only generate once. |
globalContext | object | No | Add custom tags, used to distinguish user monitoring data sources, if you need to use the tracking function, then 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 stalls, 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 is 1. |
enableLinkRumData | boolean | No | Whether to associate with RUM |
enableCustomLog | boolean | No | Whether to enable custom logs |
logLevelFilters | Array |
No | Log level filtering |
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 after reaching 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 is 1. |
traceType | enum TraceType | No | Trace type, default TraceType.ddTrace |
enableLinkRUMData | boolean | No | Whether to associate with RUM data, default false |
enableNativeAutoTrace | boolean | No | Whether to enable native network auto-tracking 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 tracked together.) |
Note:
- Please complete the SDK initialization in your top-level
index.js
file before registering the App to ensure that the SDK is fully ready before calling any other methods of the SDK.- After completing the basic configuration, proceed with RUM, Log, Trace configuration.
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
since React Native provides a wide range of libraries for creating screen navigation, by default only supports manual collection, you can use the following methods to manually start and stop views.
Custom View¶
Usage¶
/**
* View load duration.
* @param viewName view name
* @param loadTime view load duration
* @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 are using 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 are using createNativeStackNavigator();
to create a native navigation stack, it is recommended to use the screenListeners
method to start collection, which can count the page load 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 automatic collection method in the NavigationContainer
component, as follows:
Note: This method cannot collect page load 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>
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 you can manually add using the following methods.
Usage¶
/**
* Start RUM Action. RUM will bind the Action to possible triggered Resource, Error, LongTask events.
* Avoid adding multiple times within 0.1 s, the same View will only associate one Action at the same time, if the previous Action has not ended,
* the new Action will be discarded. Does not affect the Action 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 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
property. If you wish to perform some custom operations on top of automatic tracking, the SDK supports the following operations:
- Customize the
actionName
of 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 a component's click event
Can be set by adding the ft-enable-track
custom parameter, set value to false
- Add additional properties to a component's click event
Can be set by adding the ft-extra-property
custom parameter, requires value to be a Json string
<Button title="Action Add Extra Property"
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 you can manually add using the following methods.
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 you can manually add using the following methods.
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 Logging¶
Currently, the log content is limited to 30 KB, characters beyond this limit 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¶
The SDK initialization Trace Configuration can enable automatic network trace, and also supports user-defined collection, the custom collection usage and examples 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 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 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 Synchronization¶
When FTMobileConfig.autoSync
is configured as true
, no additional operations are needed, the SDK will automatically synchronize.
When FTMobileConfig.autoSync
is configured as false
, you need to actively trigger the data synchronization method to synchronize data.
Usage¶
/**
* Active data synchronization, when `FTMobileConfig.autoSync=false` is configured, you need to actively trigger this method to synchronize 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 Packaging of Symbol Files¶
Add Symbol File Automatic Packaging Script¶
Script tool: cloudcare-react-native-mobile-cli
cloudcare-react-native-mobile-cli
is a script tool that helps configure the automatic acquisition of React Native and Native sourcemaps during release builds and packages them into zip files.
Add to the package.json
development dependencies using the local file method
For example: When placing 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",
}
After adding, execute yarn install
Note: Android environment needs to add configuration 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 terminal command yarn ft-cli setup
in the React Native project directory to enable the automatic acquisition of React Native and Native sourcemaps during release builds 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 Packaging of Symbol Files¶
React Native Zip Package Packaging Instructions
Upload¶
WebView Data Monitoring¶
WebView data monitoring requires integrating the 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 a single field value 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 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 in 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 multiple environments, set 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 the environment configuration files such as .env.dubug, .env.release
};
await FTReactNativeRUM.setConfig(rumConfig);
Runtime Read and Write File Method¶
- Through data persistence methods, such as
AsyncStorage
, etc., when initializing the SDK, obtain 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('获取失败' + error);
}else {
console.log('获取成功' + 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('存储失败' + error);
}else {
console.log('存储成功');
}
})
- Finally, restart the application to take effect.
SDK Runtime Addition¶
After the SDK initialization is completed, 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 add tag data. This usage is suitable for scenarios where data acquisition is delayed, for example, 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 native development, with some pages or business processes implemented using React Native, the SDK installation initialization configuration method is as follows:
-
Installation: The installation method remains unchanged
-
Initialization: Refer to iOS SDK Initialization Configuration, Android SDK Initialization Configuration for initialization configuration in the native project
-
React Native Configuration:
RN SDK 0.3.11 support
No need to perform initialization configuration on the React Native side. If you need to automatically collect
React Native Error
, automatically collectReact Native Action
, the methods are as follows: -
Native Project Configuration:
RN SDK 0.3.11 support
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]; }; #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) }
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 react native network request set OkHttpClient
OkHttpClientProvider.setOkHttpClientFactory(new OkHttpClientFactory() {
@Override
public OkHttpClient createNewNetworkModuleClient() {
return client;
}
});
val client = OkHttpClientProvider.createClientBuilder()
.addInterceptor(FTResourceInterceptor())
.addInterceptor(FTTraceInterceptor())
.eventListenerFactory(FTResourceEventListener.FTFactory())
.build()
// Set React Native network request set OkHttpClient
OkHttpClientProvider.setOkHttpClientFactory(object : OkHttpClientFactory {
override fun createNewNetworkModuleClient(): OkHttpClient {
return client
}
})