React Native App Integration¶
Prerequisites¶
Note
If the RUM Headless service has already been activated, the prerequisites are automatically configured, and you can directly integrate the application.
- Install DataKit;
- Configure the RUM collector;
- Configure DataKit to be publicly accessible and install the IP geolocation database](../../datakit/datakit-tools-how-to.md#install-ipdb).
Application Integration¶
Note
The current React Native version only supports Android and iOS platforms.
- Navigate to User Access Monitoring > Create New App > React Native;
- Enter the app name;
- Enter the app ID;
-
Select the app integration method:
- Public DataWay: Directly receives RUM data without installing the DataKit collector.
- Local Environment Deployment: Receives RUM data after meeting the prerequisites.
Installation¶
Source Code Repository: https://github.com/GuanceCloud/datakit-react-native
Demo Repository: https://github.com/GuanceCloud/datakit-react-native/example
Run the following command in your project directory:
This will add a line like this to the package.json of your project:
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 also need to configure Guance Android Maven repository address in Gradle, both for the plugin and AAR files. For configuration details, refer to the build.gradle configuration 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 | URL address for local environment deployment (Datakit) reporting, e.g., http://10.0.0.1:9529. The default port is 9529, and the device with the SDK installed must be able to access this address. Note: Only one of datakitUrl and datawayUrl needs to be configured. |
datawayUrl | string | Yes | URL address for public Dataway reporting, obtained from the [User Access Monitoring] application, e.g., https://open.dataway.url. The device with the SDK installed must be able to access this address. Note: Only one of datakitUrl and datawayUrl needs to be configured. |
clientToken | string | Yes | Authentication token, must be used together with datawayUrl |
debug | boolean | No | Whether to allow log printing, default false |
env | string | No | Environment configuration, default prod . Any characters are allowed, it is recommended to use a single word, such as test |
envType | enum EnvType | No | Environment configuration, default EnvType.prod . Note: Only one of env and envType needs to be configured |
service | string | No | Name of the business or service to which it belongs, affecting the service field data in Log and RUM. Default: df_rum_ios , df_rum_android |
autoSync | boolean | No | Whether to automatically sync collected data to the server, default true . When set to false , manage data syncing manually using FTMobileReactNative.flushSyncData() |
syncPageSize | number | No | Set the number of entries per synchronization request. Range [5, ). Note: The larger the number of request entries, the greater the computational resources required for data synchronization |
syncSleepTime | number | No | Set the interval between synchronizations. Range [0,5000], default not set |
enableDataIntegerCompatible | boolean | No | It is recommended to enable when coexisting with web data. This configuration is used to handle compatibility issues with web data type storage. Enabled by default since version 0.3.12 |
globalContext | object | No | Add custom tags. Refer to here for adding rules |
compressIntakeRequests | boolean | No | Compress uploaded sync data using deflate, default disabled |
enableLimitWithDbSize | boolean | No | Enable limiting data size using DB, default 100MB, unit Byte. Larger databases mean higher disk pressure, default disabled. Note: After enabling, the 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 data discard rules in the database. Discard policies: FTDBCacheDiscard.discard discards new data (default), FTDBCacheDiscard.discardOldest discards old data. Supported in SDK version 0.3.10 and above |
dataModifier | object | No | Modify individual fields. Supported in SDK version 0.3.14 and above, see here for usage examples |
lineDataModifier | object | No | Modify individual data lines. Supported in SDK version 0.3.14 and above, see 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 Application Access Monitoring Console |
iOSAppId | string | Yes | app_id, applied through the Application Access Monitoring Console |
sampleRate | number | No | Sampling rate, range [0,1], 0 means no collection, 1 means full collection. Default value is 1. Scope includes all View, Action, LongTask, Error data under the same session_id |
sessionOnErrorSampleRate | number | No | Sets the error sampling rate. When a 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 includes 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 enabled, you can set the actionName along with accessibilityLabel . For more customization, please refer to here |
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 start events, default false |
enableNativeUserView | boolean | No | Whether to perform automatic tracking of Native View . For pure React Native applications, it is recommended to disable this, default false |
enableNativeUserResource | boolean | No | Whether to start automatic tracking of Native Resource . Since React-Native's network requests on iOS and Android are implemented using system APIs, enabling enableNativeUserResource allows collecting all resource data. Default false |
errorMonitorType | enum ErrorMonitorType | No | Set auxiliary monitoring information, add additional monitoring data to RUM Error data, ErrorMonitorType.battery indicates battery level, ErrorMonitorType.memory indicates memory usage, ErrorMonitorType.cpu indicates CPU utilization, default not enabled |
deviceMonitorType | enum DeviceMetricsMonitorType | No | Add monitoring data during the View cycle, DeviceMetricsMonitorType.battery (Android only) monitors the maximum output current for the current page, DeviceMetricsMonitorType.memory monitors the current app's memory usage, DeviceMetricsMonitorType.cpu monitors CPU fluctuation count, DeviceMetricsMonitorType.fps monitors screen frame rate, default not enabled |
detectFrequency | enum DetectFrequency | No | Performance monitoring sampling cycle for views, default is DetectFrequency.normal |
enableResourceHostIP | boolean | No | Whether to collect the IP address of the target domain for the request. Scope: affects only default collection when enableNativeUserResource is true . iOS: supported on iOS 13 and later. Android: Single Okhttp has an IP caching mechanism for the same domain, under the same OkhttpClient , if the server IP does not change, it will only generate once. |
globalContext | object | No | Add custom tags for distinguishing data sources of user monitoring. If you need to use tracking functionality, the parameter key should be track_id and value can be any value. Please refer to here for addition rules |
enableTrackNativeCrash | boolean | No | Whether to enable monitoring of Android Java Crash and OC/C/C++ crashes, default false |
enableTrackNativeAppANR | boolean | No | Whether to enable monitoring of Native ANR , default false |
enableTrackNativeFreeze | boolean | No | Whether to collect Native Freeze , default false |
nativeFreezeDurationMs | number | No | Set the threshold for collecting Native Freeze lag, range [100,), unit milliseconds. iOS defaults to 250ms, Android defaults to 1000ms |
rumDiscardStrategy | string | No | Discard strategy: FTRUMCacheDiscard.discard discards new data (default), FTRUMCacheDiscard.discardOldest discards old data |
rumCacheLimitCount | number | No | Local cache maximum RUM entry 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 | Filter logs by level |
globalContext | NSDictionary | No | Add custom log tags, please refer to here for adding rules |
logCacheLimitCount | number | No | Local cache maximum log entry limit [1000,), more logs mean higher disk cache pressure, default 5000 |
discardStrategy | enum FTLogCacheDiscard | No | Set log discard rules when the limit is reached. Default FTLogCacheDiscard.discard , discard discards added data, discardOldest discards old data |
Trace Configuration¶
let traceConfig: FTTractConfig = {
enableNativeAutoTrace: true,
};
await FTReactNativeTrace.setConfig(traceConfig);
Field | Type | Required | Description |
---|---|---|---|
sampleRate | number | No | Sampling rate, range [0,1], 0 means no collection, 1 means full collection. Default is 1. |
traceType | enum TraceType | No | Trace type, default TraceType.ddTrace |
enableLinkRUMData | boolean | No | Whether to associate with RUM data, default false |
enableNativeAutoTrace | boolean | No | Whether to enable native network auto-tracing for iOS NSURLSession and Android OKhttp (since React Native network requests on iOS and Android are implemented using system APIs, enabling enableNativeAutoTrace allows tracing all React Native data.) |
Note:
- Complete the SDK initialization before registering the App in your top-level
index.js
file to ensure the SDK is fully ready before calling any other SDK methods.- Perform RUM, Log, and Trace configurations after completing the basic 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
provides extensive libraries for creating screen navigation, so manual collection is supported by default. You can use the following methods to manually start and stop views.
Custom View¶
Usage¶
/**
* Duration of view loading.
* @param viewName view name
* @param loadTime view loading duration
* @returns a Promise.
*/
onCreateView(viewName:string,loadTime:number): Promise<void>;
/**
* Start view.
* @param viewName interface name
* @param property event context (optional)
* @returns a Promise.
*/
startView(viewName: string, property?: object): Promise<void>;
/**
* End view.
* @param property event context (optional)
* @returns a Promise.
*/
stopView(property?:object): Promise<void>;
Example¶
import {FTReactNativeRUM} from '@cloudcare/react-native-mobile';
FTReactNativeRUM.onCreateView('viewName', duration);
FTReactNativeRUM.startView(
'viewName',
{ 'custom.foo': 'something' },
);
FTReactNativeRUM.stopView(
{ 'custom.foo': 'something' },
);
Automatically Collect React Native View¶
If you use react-native-navigation
, react-navigation
, or Expo Router
navigation components in React Native, you can refer to the following methods for 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 One:
If you use createNativeStackNavigator();
to create a native navigation stack, it is recommended to use the screenListeners
method to start collection, which allows measuring page load times. Use 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 Two:
If you are not using createNativeStackNavigator();
, you need to add the automatic collection method in the NavigationContainer
component, as shown below:
Note: This method cannot collect page load times
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, please refer to example.
Expo Router¶
If you are using Expo Router, add the following method in the app/_layout.js file to collect data.
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 children routes in the most basic way.
return <Slot />;
}
Action¶
During SDK initialization RUM configuration, configure enableAutoTrackUserAction
and enableNativeUserAction
to enable automatic collection, or manually add them using the following methods.
Usage¶
/**
* Start a RUM Action. RUM will bind possible triggered Resource, Error, LongTask events to this Action.
* Avoid adding multiple actions within 0.1 s. Only one Action will be associated with the same View at the same time.
* New Actions will be discarded if the previous Action hasn't ended yet. Unaffected by the `addAction` method.
* @param actionName action name
* @param actionType action type
* @param property event context (optional)
* @returns a Promise.
*/
startAction(actionName:string,actionType:string,property?:object): Promise<void>;
/**
* Add an Action event. This type of data cannot be associated with Error, Resource, LongTask data and has no discard logic.
* @param actionName action name
* @param actionType action type
* @param property event context (optional)
* @returns a Promise.
*/
addAction(actionName:string,actionType:string,property?:object): Promise<void>;
Code Example¶
import {FTReactNativeRUM} from '@cloudcare/react-native-mobile';
FTReactNativeRUM.startAction('actionName','actionType',{'custom.foo': 'something'});
FTReactNativeRUM.addAction('actionName','actionType',{'custom.foo': 'something'});
More Custom Collection Operations
After enabling enableAutoTrackUserAction
, the SDK will automatically collect click operations on components with the onPress
attribute. If you want to perform some custom operations based on automatic tracking, the SDK supports the following operations:
- Customize the
actionName
for a specific 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 a specific component's click event
Add the ft-enable-track
custom parameter and set its value to false
- Add additional properties to a component's click event
Add the ft-extra-property
custom parameter, the value must be a JSON string
<Button title="Action 添加额外属性"
ft-extra-property='{"e_name": "John Doe", "e_age": 30, "e_city": "New York"}'
onPress={()=>{
console.log("btn click")
}}
/>
Error¶
Configure enableAutoTrackError
in the SDK initialization RUM configuration to enable automatic collection, or manually add using the following method.
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 Usage¶
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¶
Enable automatic collection in the SDK initialization RUM configuration by configuring enableNativeUserResource
, or manually add using the following method.
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¶
Current log content limit is 30 KB, characters exceeding 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 | Recovery |
Tracer Network Trace¶
When initializing the SDK Trace configuration, you can enable automatic network tracing. It also supports user-defined collection. The usage and example for custom collection are as follows:
Usage¶
/**
* Get trace HTTP request header data.
* @param url Requested URL
* @returns Trace request header parameters
* @deprecated use getTraceHeaderFields() instead.
*/
getTraceHeader(key:String, url: String): Promise<object>;
/**
* Get trace HTTP request header data.
* @param url Requested URL
* @returns Trace 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);
}
}
Binding and Unbinding User Information¶
Usage¶
/**
* Bind user.
* @param userId User ID.
* @param userName User name.
* @param userEmail User email
* @param extra Extra user 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 Extra user 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 unreported cached data
Usage¶
Example¶
/**
* Clear all data that has not yet been uploaded to the server.
*/
FTMobileReactNative.clearAllData();
Manually Synchronize Data¶
When FTMobileConfig.autoSync
is set to true
, no additional operation is needed, the SDK will synchronize data automatically.
When FTMobileConfig.autoSync
is set to false
, you need to manually trigger the data synchronization method to perform data synchronization.
Usage¶
/**
* Manually synchronize data. When `FTMobileConfig.autoSync=false` is configured, this method needs to be manually triggered to perform data synchronization.
* @returns a Promise.
*/
flushSyncData():Promise<void>;
Example¶
Adding Custom Tags¶
Usage¶
/**
* Add custom global parameters. Applies to RUM and 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 and 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'});
Upload Symbol Files¶
Automatically Package Symbol Files¶
Add Automatic Packaging Script for Symbol Files¶
Script tool: cloudcare-react-native-mobile-cli
cloudcare-react-native-mobile-cli
is a script tool that helps configure release builds to automatically obtain React Native and Native sourcemaps and package them into zip files.
Add to package.json
development dependencies using the local file method.
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",
}
After adding, execute yarn install
.
Note: Android environment requires adding configuration Gradle Plugin ft-plugin, version requirement: >=1.3.4
Add the usage and parameter settings of the Plugin
in the build.gradle
file of the main module of the project:
apply plugin: 'ft-plugin'
FTExt {
//showLog = true
autoUploadMap = true
autoUploadNativeDebugSymbol = true
generateSourceMapOnly = true
}
Execute Configuration Command¶
Execute terminal command yarn ft-cli setup
in the React Native project directory to automatically obtain React Native and Native sourcemaps during release build and package them into zip files. If the following log appears, the setup was successful.
➜ 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.
Zip file location after release build:
iOS: Under the iOS folder (./ios/sourcemap.zip)
Android: In the RN project directory (./sourcemap.zip)
Manual Packaging of Symbol Files¶
React Native Zip Package Instructions
Upload¶
WebView Data Monitoring¶
To monitor WebView data, you need to integrate the Web Monitoring SDK on the page accessed by the WebView.
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)
-
Purpose: 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 Line Data Modification (lineDataModifier)
-
Purpose: Modify specified field values in certain types 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 Types 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"},
}
}
Example of Using Custom Tags¶
Compilation Configuration Method¶
- Use
react-native-config
to configure multi-environments, setting the corresponding custom tag values in different environments.
let rumConfig: FTRUMConfig = {
iOSAppId: iOSAppId,
androidAppId: androidAppId,
monitorType: MonitorType.all,
enableTrackUserAction:true,
enableTrackUserResource:true,
enableTrackError:true,
enableNativeUserAction: false,
enableNativeUserResource: false,
enableNativeUserView: false,
globalContext:{"track_id":Config.TRACK_ID}, //.env.debug、.env.release etc. configuration files set the environment
};
await FTReactNativeRUM.setConfig(rumConfig);
Runtime File Reading/Writing Method¶
- Through data persistence methods, such as
AsyncStorage
, get 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('获取失败' + error);
}else {
console.log('获取成功' + result);
if( result != undefined){
rumConfig.globalContext = {"track_id":result};
}
}
resolve(FTReactNativeRUM.setConfig(rumConfig));
})
});
- Add or change custom tags to a file anywhere.
AsyncStorage.setItem("track_id",valueString,(error)=>{
if (error){
console.log('存储失败' + error);
}else {
console.log('存储成功');
}
})
- Finally, restart the application to take effect.
Adding Dynamically at SDK Runtime¶
After the SDK has been initialized, use FTReactNativeRUM.appendGlobalContext(globalContext)
, FTReactNativeRUM.appendRUMGlobalContext(globalContext)
, FTReactNativeRUM.appendLogGlobalContext(globalContext)
to dynamically add tags. Once set, they take effect immediately. Subsequent reported RUM or Log data will automatically include the tag data. This usage is suitable for scenarios where data needs to be delayed, such as needing to retrieve tag data via a network request.
//SDK Initialization Pseudocode, Getting Info
FTMobileReactNative.sdkConfig(config);
function getInfoFromNet(info:Info){
let globalContext = {"delay_key":info.value}
FTMobileReactNative.appendGlobalContext(globalContext);
}
Hybrid Development with Native and React Native¶
If your project is natively developed, but uses React Native for some pages or business processes, the installation and initialization configuration methods for the SDK are as follows:
-
Installation: The installation method remains unchanged Installation
-
Initialization: Please refer to iOS SDK Initialization Configuration, Android SDK Initialization Configuration to initialize and configure within the native project
-
React Native Configuration:
RN SDK version 0.3.11 and above support
There is no need to re-initialize and configure on the React Native side. If you need to automatically collect
React Native Error
and automatically collectReact Native Action
, follow the steps below: -
Native Project Configuration:
RN SDK version 0.3.11 and above support
When enabling RUM Resource auto-collection, filter out only React Native symbolization call requests and Expo logging call requests that occur in the development environment. The method is 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) }
Specific usage examples can refer to example.
Manual Configuration for Android Resource Collection¶
If you encounter some low-version environments or conflicts with other SDKs, you will 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当前翻译进度已完成,请提供新的内容以继续翻译。