Skip to content

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.

Application Integration

Note

The current React Native version only supports Android and iOS platforms.

  1. Go to User Access Monitoring > Create Application > React Native;
  2. Create two applications for React Native Android and React Native iOS respectively to receive RUM data from Android and iOS platforms;
  3. Enter the corresponding application name and application ID for each platform's application;
  4. 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:

npm install @cloudcare/react-native-mobile

This will add the following line to the package.json:

"dependencies": {    
   "@cloudcare/react-native-mobile: [lastest_version],
   ···
}

Additional Android Integration Configuration:

  • 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 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,
  };

 //Use Public DataWay
 let config: FTMobileConfig = {
    datawayUrl: datawayUrl,
    clientToken: clientToken
  };
await FTMobileReactNative.sdkConfig(config);
Field Type Required Description
datakitUrl string Yes Local environment deployment (Datakit) reporting URL address, example: http://10.0.0.1:9529, default port 9529, the device installing the SDK must be able to access this address. Note: Either datakitUrl or datawayUrl must be configured
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: Either datakitUrl or datawayUrl must be configured
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: Either env or envType should 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 sync 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 sync 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 please refer to here
compressIntakeRequests boolean No Deflate compression for uploaded sync 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 off.
Note: After enabling, Log configuration logCacheLimitCount and RUM configuration rumCacheLimitCount will be invalid. Supported in SDK version 0.3.10 and above
dbCacheLimit number No DB cache size limit. 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 individual fields. Supported in SDK version 0.3.14 and above, usage example see here
lineDataModifier object No Modify single 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 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 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, can be used with accessibilityLabel to set actionName, more custom operations please 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, pure React Native applications are recommended to turn off, 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 off
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 off
detectFrequency enum DetectFrequency No View performance monitoring sampling cycle, default DetectFrequency.normal
enableResourceHostIP boolean No Whether to collect the IP address of the request target domain. Scope: only affects the default collection when enableNativeUserResource is true. iOS: supported in >= iOS 13. Android: Single Okhttp has an IP caching mechanism for the same domain, 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 considerations please 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 lag, 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 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 please 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 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 automatic 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.)

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.
import App from './App';

async function sdkInit() {
  await FTMobileReactNative.sdkConfig(config);
  await FTReactNativeRUM.setConfig(rumConfig);
  ....
}
initSDK();
AppRegistry.registerComponent('main', () => App);

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 to create screen navigation, so by default only manual collection is supported, 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 interface name
 * @param property event context (optional)
 * @returns a Promise.
 */
startView(viewName: string, property?: object): Promise<void>;
/**
 * View end.
 * @param property event context (optional)
 * @returns a Promise.
 */
stopView(property?:object): Promise<void>;
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, so that the page load duration 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 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, please 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 manually add.

Usage

/**
 * Start RUM Action. RUM will bind the Resource, Error, LongTask events that this Action may trigger.
 * 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 want to perform some custom operations on the basis 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 the click event of a component

Can be set by adding the ft-enable-track custom parameter, set the value to false

  <Button title="Action Click" 
          ft-enable-track="false"
          onPress={()=>{
                console.log('btn click');
          }}
  />
  • Add additional properties 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 Properties"
          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 manually add.

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 manually add.

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 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 Recovery

Tracer Network Trace

SDK initialization Trace Configuration can enable automatic network trace, also supports user-defined collection, 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'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

/**
 * Shut down the running objects in the SDK
 */
shutDown():Promise<void>

Example

FTMobileReactNative.shutDown();

Clear SDK Cache Data

Use FTMobileReactNative to clear unuploaded cache data.

Usage

/**
 * Clear all data that has not been uploaded to the server.
 */
clearAllData():Promise<void>

Example

/**
 * Clear all data that has not been uploaded to the server.
*/
FTMobileReactNative.clearAllData();

Active Data Synchronization

When configuring FTMobileConfig.autoSync as true, no additional operations are required, the SDK will automatically synchronize.

When configuring FTMobileConfig.autoSync as false, you need to actively trigger the data synchronization method to synchronize data.

Usage

/**
 * Actively synchronize data, when configuring `FTMobileConfig.autoSync=false`, you need to actively trigger this method to synchronize data.
 * @returns a Promise.
 */
flushSyncData():Promise<void>;

Example

FTMobileReactNative.flushSyncData();

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 that helps configure the release build to automatically obtain React Native and Native sourcemaps and package them as zip files.

Add to the package.json development dependencies using the local file method.

For example: When placing ft-react-native-mobile-cli.tgz in the React Native project directory.

 "devDependencies": {
    "@cloudcare/react-native-mobile-cli":"file:./ft-react-native-mobile-cli-v1.0.0.tgz",
  }

After adding, execute yarn install.

Note: 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 automatically obtain React Native and Native sourcemaps during the release build and package them as 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

File Upload and Delete

WebView Data Monitoring

WebView data monitoring requires integrating 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 the device_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 the view_url field value of all view type data to "xxx"
  • measurement data type list:
    • RUM data: view, resource, action, long_task, error
    • Log data: log
  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

  1. Use react-native-config to 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}, //Set in the environment files such as .env.dubug, .env.release
    };

 await FTReactNativeRUM.setConfig(rumConfig); 

Runtime File Read and Write Method

  1. Through data persistence methods, such as AsyncStorage, etc., obtain the stored custom tags when initializing the SDK.
 let rumConfig: FTRUMConfig = {
      iOSAppId: iOSAppId,
      androidAppId: androidAppId,
      monitorType: MonitorType.all,
      enableTrackUserAction:true,
      enableTrackUserResource:true,
      enableTrackError:true,
      enableNativeUserAction: false,
      enableNativeUserResource: false,
      enableNativeUserView: false,
    };
 await new Promise(function(resolve) {
       AsyncStorage.getItem("track_id",(error,result)=>{
        if (result === null){
          console.log('Get failed' + error);
        }else {
          console.log('Get success' + result);
          if( result != undefined){
            rumConfig.globalContext = {"track_id":result};
          }
        }
        resolve(FTReactNativeRUM.setConfig(rumConfig));
      })
     });
  1. 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');
    }
})
  1. 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. 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 obtained through network requests.

//SDK initialization pseudo code, obtain
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, and some pages or business processes are implemented using React Native, the SDK installation initialization configuration method is as follows:

  • Installation: Installation method remains the same

  • Initialization: Please 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 initialize configuration on the React Native side. If you need to automatically collect React Native Error, automatically collect React Native Action, the method is as follows:

    import {FTRumActionTracking,FTRumErrorTracking} from '@cloudcare/react-native-mobile';
    //Enable automatic collection of react-native component clicks
    FTRumActionTracking.startTracking();
    //Enable automatic collection of react-native Error
    FTRumErrorTracking.startTracking();
    
  • 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 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
    
    import FTMobileReactNativeSDK
    import FTMobileSDK
    
    let rumConfig = FTRumConfig(appId: rumAppId)
    rumConfig.enableTraceUserResource = true
    #if DEBUG
    rumConfig.resourceUrlHandler = { (url: URL) -> Bool in
       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, please 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
    }
})

Android

iOS

Frequently Asked Questions

Feedback

Is this page helpful? ×