Skip to content

React Native Application Integration


Prerequisites

Note

If the RUM Headless service has been activated, the prerequisites are automatically configured, and the application can be directly integrated.

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 separate applications for React Native Android and React Native iOS to receive RUM data from Android and iOS platforms respectively;
  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 file:

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

Additional Configuration for Android Integration:

  • Configure the Gradle Plugin ft-plugin to collect App launch events and network request data, as well as native Android events (page navigation, click events, Native network requests, WebView data).
  • Ensure that the Guance Android Maven repository address is configured in Gradle for both the Plugin and AAR. Refer to the build.gradle configuration in the example for details.

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, e.g., 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, e.g., 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, e.g., test
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, affecting the service field data in Log and RUM. Default: df_rum_ios, df_rum_android
autoSync boolean No Whether to automatically sync data to the server after collection, default true. When false, use FTMobileReactNative.flushSyncData() to manage data synchronization manually
syncPageSize number No Set the number of entries per sync request. Range [5,). Note: A larger number of entries means more computational resources are used for data synchronization
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. Enabled by default in versions after 0.3.12
globalContext object No Add custom tags. Add rules refer to here
compressIntakeRequests boolean No Compress the uploaded sync data with deflate, default off
enableLimitWithDbSize boolean No Enable using db to limit data size, default 100MB, unit Byte. Larger databases increase 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 a single field. Supported in SDK version 0.3.14 and above, usage example see here
lineDataModifier object No Modify a single line 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 value is 1. Scope is all View, Action, LongTask, Error data under the same session_id
sessionOnErrorSampleRate number No Set the error collection rate. When a 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 value 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 launch events, default false
enableNativeUserView boolean No Whether to track Native View automatically. It is 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, all resource data can be collected after enabling enableNativeUserResource. 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 (Android only) monitors the maximum current output 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 period, 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 on >= iOS 13. Android: Single Okhttp has an IP cache mechanism for the same domain. For the same OkhttpClient, if the server IP does not change, it will only be generated once.
globalContext object No Add custom tags for user monitoring data source differentiation. If tracking is needed, the parameter key should be track_id, value can be any value. Add rule considerations 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 count limit [10_000,), default 100_000

Log Configuration

let logConfig: FTLogConfig = {
      enableCustomLog: true,
      enableLinkRumData: true,
    };
await FTReactNativeLog.logConfig(logConfig);
Field Type Required Description
sampleRate number No Sampling rate, range [0,1], 0 means no collection, 1 means full collection, default value is 1.
enableLinkRumData boolean No Whether to associate with RUM data
enableCustomLog boolean No Whether to enable custom logs
logLevelFilters Array No Log level filtering
globalContext NSDictionary No Add custom tags to logs, add rules refer to here
logCacheLimitCount number No Local cache maximum log entry count limit [1000,), larger logs mean more disk cache pressure, default 5000
discardStrategy enum FTLogCacheDiscard No Set the log discard rule when the log limit is reached. Default FTLogCacheDiscard.discard, discard discard appended data, discardOldest discard old data

Trace Configuration

 let traceConfig: FTTractConfig = {
      enableNativeAutoTrace: true, 
    };
await FTReactNativeTrace.setConfig(traceConfig);
Field Type Required Description
sampleRate number No Sampling rate, range [0,1], 0 means no collection, 1 means full collection, default value is 1.
traceType enum TraceType No Trace type, default TraceType.ddTrace
enableLinkRUMData boolean No Whether to associate with RUM data, default false
enableNativeAutoTrace boolean No Whether to enable native network auto-tracing iOS NSURLSession, Android OKhttp (Since React Native network requests are implemented using system APIs on iOS and Android, all React Native data can be traced after enabling enableNativeAutoTrace.)

Note:

  • Please complete the SDK initialization in your top-level index.js file before registering the App to ensure the SDK is fully ready before calling any other SDK methods.
  • Complete the basic configuration before configuring RUM, Log, and Trace.
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 is only supported manually by default due to the wide range of libraries provided by React Native for creating screen navigation. You can manually start and stop views using the following methods.

Custom View

Usage
/**
 * View loading time.
 * @param viewName view name
 * @param loadTime view loading time
 * @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. This allows for the collection of page loading time, as shown below:

  import {FTRumReactNavigationTracking} from './FTRumReactNavigationTracking';
  import { createNativeStackNavigator } from '@react-navigation/native-stack';
  const Stack = createNativeStackNavigator();

  <Stack.Navigator  screenListeners={FTRumReactNavigationTracking.StackListener} initialRouteName='Home'>
          <Stack.Screen name='Home' component={Home}  options={{ headerShown: false }} />
          ......
          <Stack.Screen name="Mine" component={Mine} options={{ title: 'Mine' }}/>
  </Stack.Navigator>
  • Method 2:

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 loading time

  import {FTRumReactNavigationTracking} from './FTRumReactNavigationTracking';
  import type { NavigationContainerRef } from '@react-navigation/native';

  const navigationRef: React.RefObject<NavigationContainerRef<ReactNavigation.RootParamList>> = React.createRef();
  <NavigationContainer ref={navigationRef} onReady={() => {
        FTRumReactNavigationTracking.startTrackingViews(navigationRef.current);
      }}>
        <Stack.Navigator initialRouteName='Home'>
          <Stack.Screen name='Home' component={Home}  options={{ headerShown: false }} />
          .....
          <Stack.Screen name="Mine" component={Mine} options={{ title: 'Mine' }}/>
        </Stack.Navigator>
   </NavigationContainer>

For specific usage examples, refer to the 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 manually add actions using the following methods.

Usage

/**
 * Start RUM Action. RUM will associate this Action with possible Resource, Error, LongTask events.
 * Avoid adding multiple times within 0.1 s. Only one Action can be associated with the same View at the same time. If the previous Action has not ended,
 * the new Action will be discarded. Does not affect Actions added with 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, 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>;

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 events 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 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 manually add errors 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 manually add resources 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 Log Printing

Currently, the log content is limited to 30 KB, and any excess characters will be truncated.

Usage

/**
 * Output log.
 * @param content log content
 * @param status  log status
 * @param property log context (optional)
 */
logging(content:String,logStatus:FTLogStatus|String,property?:object): Promise<void>;

Example

import { FTReactNativeLog, FTLogStatus } from '@cloudcare/react-native-mobile';
// logStatus:FTLogStatus
FTReactNativeLog.logging("info log content",FTLogStatus.info);
// logStatus:string
FTReactNativeLog.logging("info log content","info");

Log Levels

Method Name Meaning
FTLogStatus.info Info
FTLogStatus.warning Warning
FTLogStatus.error Error
FTLogStatus.critical Critical
FTLogStatus.ok Recovery

Tracer Network Trace

In the SDK initialization Trace Configuration, you can enable automatic network trace, or manually collect traces using the following methods:

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()

Shutdown SDK

Use FTMobileReactNative to shutdown the SDK.

Usage

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

Example

FTMobileReactNative.shutDown();

Clear SDK Cache Data

Use FTMobileReactNative to clear unsynced 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();

Manually Sync Data

When FTMobileConfig.autoSync is set to true, no additional operations are needed, the SDK will automatically sync.

When FTMobileConfig.autoSync is set to false, you need to manually trigger the data sync method to sync data.

Usage

/**
 * Manually sync data. When `FTMobileConfig.autoSync=false`, you need to manually trigger this method to sync 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 automatic retrieval of React Native and Native sourcemaps during release builds and packages them into zip files.

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

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

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

After adding, execute yarn install.

Note: Android environment requires adding 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 yarn ft-cli setup command in the terminal in the React Native project directory to automatically retrieve 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 location:

iOS: In the iOS folder (./ios/sourcemap.zip)

Android: In the 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 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 the device_uuid field value in the target data with "xxx"

Single Line Data Modification (lineDataModifier)

  • Function: Modify the specified field value in a certain type of data

  • Parameter format: {measurement: {key: newValue}}

  • Example: {"view": {"view_url": "xxx"}} will modify the view_url field value in 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 like .env.dubug, .env.release, etc.
    };

 await FTReactNativeRUM.setConfig(rumConfig); 

Runtime Read/Write File Method

  1. Use data persistence methods such as AsyncStorage, etc., to retrieve stored custom tags during SDK initialization.
 let rumConfig: FTRUMConfig = {
      iOSAppId: iOSAppId,
      androidAppId: androidAppId,
      monitorType: MonitorType.all,
      enableTrackUserAction:true,
      enableTrackUserResource:true,
      enableTrackError:true,
      enableNativeUserAction: false,
      enableNativeUserResource: false,
      enableNativeUserView: false,
    };
 await new Promise(function(resolve) {
       AsyncStorage.getItem("track_id",(error,result)=>{
        if (result === null){
          console.log('Failed to retrieve' + error);
        }else {
          console.log('Retrieved successfully' + result);
          if( result != undefined){
            rumConfig.globalContext = {"track_id":result};
          }
        }
        resolve(FTReactNativeRUM.setConfig(rumConfig));
      })
     });
  1. Add or change custom tags to the file anywhere.
AsyncStorage.setItem("track_id",valueString,(error)=>{
    if (error){
        console.log('Failed to store' + error);
    }else {
        console.log('Stored successfully');
    }
})
  1. Finally, restart the application to take effect.

SDK Runtime Addition

After SDK initialization, 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 include the tag data. This usage is suitable for scenarios where data is obtained with a delay, such as when tag data needs to be obtained through network requests.

//SDK initialization pseudo code, get
FTMobileReactNative.sdkConfig(config);

function getInfoFromNet(info:Info){
    let  globalContext = {"delay_key":info.value}
    FTMobileReactNative.appendGlobalContext(globalContext);
}

Native and React Native Hybrid Development

If your project is developed natively, with some pages or business processes implemented using React Native, the SDK installation and initialization configuration methods are as follows:

  • Installation:

    After RN SDK installation is successful, the native side does not need to install Android / iOS SDK again. If already installed, to prevent version conflicts, we recommend using this solution:

    In the Android environment, add the following dependency settings in your android/app/build.gradle file:

    // Version set by Guance RN SDK
    implementation 'com.cloudcare.ft.mobile.sdk.tracker.agent:ft-sdk
    implementation 'com.cloudcare.ft.mobile.sdk.tracker.agent:ft-native
    
    You can also view the corresponding native SDK version information through node_modules/@cloudcare/react-native-mobile/android/build.gradle

    In the iOS environment, react-native manages dependencies through cocoapods. For iOS SDK installation, please also use cocoapods. Add the following settings in your ios/Podfile file:

    // Version set by Guance RN SDK
    pod 'FTMobileSDK'
    
    You can also view the corresponding native SDK version information through node_modules/@cloudcare/react-native-mobile/FTMobileReactNativeSDK.podspec

  • 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 for initialization configuration on the React Native side. If automatic collection of React Native Error, automatic collection of React Native Action is needed, the methods are 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, 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
    
    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.ft.sdk.reactnative.utils.ReactNativeUtils;
    import com.ft.sdk.FTRUMConfig;
    
    FTRUMConfig rumConfig = new FTRUMConfig().setRumAppId(rumAppId);
    rumConfig.setEnableTraceUserResource(true);
    if (BuildConfig.DEBUG) {
        rumConfig.setResourceUrlHandler(new FTInTakeUrlHandler() {
          @Override
          public boolean isInTakeUrl(String url) {
            return ReactNativeUtils.isReactNativeDevUrl(url);
          }
        });
      }
    
    import com.ft.sdk.reactnative.utils.ReactNativeUtils
    import com.ft.sdk.FTRUMConfig
    
    val rumConfig = FTRUMConfig().setRumAppId(rumAppId)
        rumConfig.isEnableTraceUserResource = true
        if (BuildConfig.DEBUG) {
          rumConfig.setResourceUrlHandler { url ->
            return@setResourceUrlHandler ReactNativeUtils.isReactNativeDevUrl(url)
        }
    

For specific usage examples, refer to the example.

Android Resource Collection Manual Configuration

If encountering low version environments or other SDK conflicts, manual Android Resource data tracking is needed.

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? ×