![N|Solid](https://assets.dynatrace.com/content/dam/dynatrace/misc/dynatrace_web.png)
Dynatrace React Native Plugin
The Dynatrace React Native plugin helps to auto-instrument your React Native app with Dynatrace OneAgent for Android and iOS and provides an API to add manual instrumentation. It is compatible with raw, ejected React Native projects. Which means it works with Expo Kit, but not with Expo.
Currently this plugin is available as an early access version. If you want to test it, please sign up for the EAP.
Supported features
The following features are currently supported:
- Auto-instrumentation using OneAgent for Android and iOS
- User actions for AppStart and native controls
- Web requests
- Crashes
- React-native Auto-instrumentation
- User actions for touches Touchables, Buttons, Pickers, RefreshControl and lifecycle events such as render(), didMount() and didUpdate()
- Reporting React Native errors
- Manual instrumentation
- Typescript bindings to add manual instrumentation
Requirements
- React Native >= 0.48
- Gradle >= 5.0 (How to upgrade?)
- React Native instrumentation => ES6 Classes
- For Android users: Minimum SDK version 15
- For iOS users: Minimum iOS 6
Quick Setup
- Eject your app
- Install plugin
- Register Dynatrace transformer
- Setup configuration
- Run auto instrumentation
- Build and run your app
Advanced topics
Troubleshooting
Quick Setup
1. Eject your app
- If your app is not yet ejected do it now by calling
react-native eject
. This generates the Android and iOS folders that are required by the plugin.
2. Install the plugin
- Install the plugin by calling
react-native install @dynatrace/react-native-plugin
. - Only < RN 0.60.0 (Which don't use autolinking) : Call
react-native link @dynatrace/react-native-plugin
which will automatically add the dependencies to your native projects.
Troubleshooting
- Expo-Kit only: the installation script does not get triggered automatically. You can call it manually by running
node ./node_modules/@dynatrace/react-native-plugin/scripts/install.js
- If for some reason (e.g. seperate native projects)
react-native link
does not work as expected, you can manually add the iOS agent to your project.
3. Register the Dynatrace transform
Depending on your react native version you will need to use a different way to register the transformer. If you don't know your version, you can enter react-native --version
in your terminal to get it.
RN >= 0.57
In your projects root, either create or extend (>= RN 0.59) metro.config.js
/ (>= RN 0.57 - 0.59) rn-cli.config.js
so it contains the transformer.babelTransformerPath
property:
module.exports = {
transformer: {
babelTransformerPath: require.resolve('@dynatrace/react-native-plugin/lib/dynatrace-transformer')
},
reporter: require("@dynatrace/react-native-plugin/lib/dynatrace-reporter")
};
RN < 0.57
Add this to your rn-cli.config.js
(make one if you don't have one already):
module.exports = {
getTransformModulePath() {
return require.resolve('@dynatrace/react-native-plugin/lib/dynatrace-transformer');
},
getSourceExts() {
return ['js'];
}
}
4. Setup dynatrace.config.js
-
If you were upgrading from a previous version of this plugin, you'll notice that the file format changed. Your old configuration is still available in dynatrace.config
and you have to copy your values to the new dynatrace.config.js
.
-
Define a mobile app in Dynatrace and open the Mobile app instrumentation settings. Open the dynatrace.config.js
in the root directory that was already created by the npm install script and update the applicationId, beaconUrl for Android and DTXApplicationID and DTXBeaconURL for iOS.
-
Attention : You need to define your components which you want to see lifecycle instrumented. You can see an example here. This is important as you will only see Application startup and Touches out of the box.
If you want to know more details about the configuration you can find them in the Advanced Topics section.
5. Build and run your app
-
Only RN <= 0.59.10: Execute npm run instrumentDynatrace
in the root of your React Native project. This will configure both Android and iOS project with the settings from dynatrace.config.js
. You can use the same custom arguments as mentioned above.
-
Use react-native run-android
or react-native run-ios
to rebuild and run your app. If you want to specify custom paths, you can do this via custom arguments.
Advanced topics
Manual instrumentation
To be able to use the API of the React Native plugin you need to do import and initialize the API:
import { Dynatrace, Platform } from '@dynatrace/react-native-plugin';
Create Manual Action
To create a manual action that is called "MyButton tapped"
you just need to use the following code. The leaveAction will close the action again. It is possible to report values for this action before closing, see next section Report Values.
let myAction = Dynatrace.enterAction("MyButton tapped");
myAction.leaveAction();
Report Values
For any open action you can report certain values. The following APIs are available on the Action:
reportDoubleValue(valueName: string, value: number, platform?: Platform): void
reportError(errorName: string, errorCode: number, platform?: Platform): void
reportEvent(eventName: string, platform?: Platform): void
reportIntValue(valueName: string, value: number, platform?: Platform): void
reportStringValue(valueName: string, value: string, platform?: Platform): void
In order to report an String value you would need to do the following:
let myAction = Dynatrace.enterAction("MyButton tapped");
myAction.reportStringValue("ValueName", "ImportantValue");
myAction.leaveAction();
If you look at the API calls you will see the optional parameter platform?: Platform
. This parameter offers you the possibility to report values only for a specific platform. See Platform independent reporting if you want to learn more about this.
Identify User
It is possible to identify a user and tag the current session with a name. You need to do the following call:
Dynatrace.identifyUser("User XY");
Crash Reporting
Crash reporting is enabled by default. The Mobile Agent captures all unhandled exceptions/errors and sends the crash report immediately to the server. With this API you can activate or deactive crash reporting. If you want to change this behaviour via this API you need to enable/activate userOptIn
, see following section and set privacy settings.
async isCrashReportingOptedIn(platform?: Platform): Promise<boolean>
setCrashReportingOptedIn(crashReporting: boolean, platform?: Platform): void
DataCollection
The privacy API methods allow you to dynamically change the data-collection level based on the individual preferences of your end users. Each end user can select from three data-privacy levels:
export enum DataCollectionLevel {
Off, User, Performance
}
- Off: Native Agent won't capture any monitoring data.
- Performance: Native Agent will only capture anonymous performance data. Monitoring data that can be used to identify individual users, such as user tags and custom values, won't be captured.
- User: Native Agent will capture both performance and user data. In this mode, Native Agent recognizes and reports on users who re-visit in future sessions.
The API to get and set the current level looks like this.
async getDataCollectionLevel(platform?: Platform): Promise<DataCollectionLevel>
setDataCollectionLevel(dataCollectionLevel: DataCollectionLevel, platform?: Platform): void
Report GPS Location
You can report latitude and longitude and specify an optional platform.
setGPSLocation(latitude: number, longitude: number, platform?: Platform): void
Platform independent reporting
You probably noticed that each method has an addition optional parameter platform
of type Platform
. You can use this to only trigger manual instrumentation for a specific OS. The available values are: Platform.Ios
, Platform.Android
. Default is that it will work on any platform. Otherwise it is passed only to the relevant OS. For example:
let myAction = Dynatrace.enterAction("MyButton tapped", Platform.Ios);
myAction.leaveAction("ios");
let myAction = Dynatrace.enterAction("MyButton tapped", Platform.Android);
myAction.leaveAction("android");
let myAction = Dynatrace.enterAction("MyButton tapped");
myAction.leaveAction();
Custom arguments for instrumentation script
Our scripts assumes that the usual react native project structure is given. The following arguments can be specified for our instrumentation script if the project structure is different.
gradle=C:\MyReactAndroidProject\build.gradle
- the location of the root build.gradle file. We will assume that the other gradle file resides in /app/build.gradle
. This will add the whole agent dependencies automatically for you and will update the configuration.plist=C:\MyReactIOSProject\projectName\info.plist
- Tell the script where your info.plist file is. The plist file is used for updating the configuration for the agent.config=C:\SpecialFolderForDynatrace\dynatrace.config.js
- If you have not got your config file in the root folder of the React Native project but somewhere else.
Examples:
react-native run-android --config
Manual Adding iOS Agent to Project
Adding the iOS agent manually depends on wether you use CocoaPods or not.
With CocoaPods support
insert the following in your Podfile:
pod 'react-native-dynatrace', :path => '../node_modules/@dynatrace/react-native-plugin'
Without CocoaPods support
- Open your project in Xcode
- Run open
node_modules/@dynatrace/react-native-plugin/ios
- Drag
DynatraceRNBridge.xcodeproj
into your Libraries group - Select your main project in the navigator to bring up settings
- Under Build Phases expand the Link Binary With Libraries header
- Scroll down and click the + to add a library
- Find and add
libRNDynatrace.a
under the Workspace group - ⌘+B
Structure of the dynatrace.js
file
The configuration is structured in the following way
module.exports = {
react : {
// Configuration for React Native instrumentation
},
android : {
// Configuration for Android auto instrumentation
},
ios : {
// Configuration for iOS auto instrumentation
}
}
React Block
The react
configuration block contains all settings regarding the react instrumentation. The following options are possible:
Input
react : {
input : {
instrument(filename) => {
return true;
}
}
}
The instrument function above expects you to return true
or false
. In this case all files will be instrumented for capturing user input.
Lifecycle
react : {
lifecycle : {
includeUpdate : false,
instrument(filename) => {
// This will only capture inputs in files in the path src/screens/
return filename.startsWith(require('path').join('src', 'screens'));
}
}
}
The instrument function above expects you to return true
or false
. In this case all files in the folder src/screens/
will be instrumented for capturing user input.
Attention: it is important that you input all files there where you wish lifecycle instrumentation. Probably this should contain all your "real" screens. If you return true
for this function we will really report ALL lifecycle events, which is a lot in React Native.
Debug Mode
react: {
debug: true
}
This will activate the debug mode. You will get more console output during instrumentation and at runtime.
Android Block
The Android block is just a wrapper for the Android configuration you find in the WebUI (in the Mobile Application Settings). Just copy the content into the following block:
android : {
config : `CONTENT_OF_ANDROID_CONFIG`
}
The content of the config
block will be directly copied to the gradle file. If you want to know more about the possible configuration options have a look into the DSL documentation of our gradle plugin. (You can find it locally in @dynatrace\react-native-plugin\android\eap\docs\plugin\dsl
)
iOS Block
The iOS block is just a wrapper for the iOS configuration you find in the WebUI (in the Mobile Application Settings). Just copy the content into the following block:
ios : {
config : `CONTENT_OF_IOS_CONFIG`
}
The content of the config
block will be directly copied to the plist file, so you can use every setting that is possible and you find in the official Mobile Agent documentation.
Define build stages in dynatrace.config.js
If you have several stages like debug, qa or production you probably want to seperate them and let them report in different applications. This is possible with a different configuration.
Android
In Android you can enter all the information in the config file. So the following dynatrace {} block should be inserted into the android config variable in your dynatrace.config.js file.
android : {
config : `
dynatrace {
configurations {
dev {
variantFilter "Debug" // build type name is upper case because a product flavor is used
// other variant-specific properties
}
demo {
variantFilter "demo" // the first product flavor name is always lower case
// other variant-specific properties
}
prod {
variantFilter "Release" // build type name is upper case because a product flavor is used
// other variant-specific properties
}
}
}
`
}
the above will lead to the following result:
> Task :app:printVariantAffiliation
Variant 'demoDebug' will use configuration 'dev'
Variant 'demoRelease' will use configuration 'demo'
Variant 'paidDebug' will use configuration 'dev'
Variant 'paidRelease' will use configuration 'prod'
In all those blocks you can define your different applicationIds. You can even use a different environment.
iOS
In iOS you can define some variables in the dynatrace.config.js file. Those variables should then be inserted in a prebuild script. The following properties should be inserted into the iOS config variable in your dynatrace.config.js file.
ios: {
config: `
<key>DTXApplicationID</key>
<string>${APPLICATION_ID}</string>
<key>DTXBeaconURL</key>
<string>Your Beacon URL</string>
`
}
The variable ${APPLICATION_ID} must then be inserted with a prebuild script. If you want to know more about this, you should look into: https://medium.com/@andersongusmao/xcode-targets-with-multiples-build-configuration-90a575ddc687
User Opt In Mode
Specifies if the user has to opt-in for monitoring. If enabled you need to specify the privacy setting. See the API section for more information.
Android
android: {
config: `
dynatrace {
configurations {
defaultConfig {
autoStart{
...
userOptIn true
}
}
}
}
`
}
iOS
ios: {
config: `
<key>DTXUserOptIn</key>
</true>
`
}
Native Agent debug logs
If the instrumentation runs through and your application starts but you see no data you probably need to dig deeper why the Agents are not sending any data. Opening up a support case is a great idea, but gathering logs first is even better. How do you gather logs?
Android
Add the following configuration snippet to your other configuration in dynatrace.config.js (Maybe beneath the autoStart block. The whole structure is only visible, so you know where the config belongs) and run npm run instrumentDynatrace :
android: {
config: `
dynatrace {
configurations {
defaultConfig {
autoStart{
...
}
debug.agentLogging true
}
}
}
`
}
iOS
Add the following configuration snippet to your other configuration in dynatrace.config.js (The whole structure is only visible, so you know where the config belongs) and run npm run instrumentDynatrace :
ios: {
config: `
<key>DTXLogLevel</key>
<string>ALL</string>
`
}
How does Dynatrace determine the user action name?
- React views
- displayName: We look if React views have a display name set (using displayName property).
- class name :If the display name is not available, the class name will be used by taking the name property from the constructor.
- Touchables
- Accessibility label
- If both are not set, it will search for an inner text
- If it is an Image Button it will try to search for a source
- Buttons
- Button Title
- Accessibility label
- If it is an Image Button it will try to search for a source
- If nothing found, it will search for an inner text
If you minify your react native code you can use the keep_classname setting to preserve the class name.
Updating to Gradle 5
Updating Gradle only affects your Android build. To Update your project to Gradle 5 you have to modify 3 files in your Android folder.
ProjectFolder\android\gradle\wrapper\gradle-wrapper.properties
Update the distributionUrl to get a higher gradle version.
distributionUrl=https\://services.gradle.org/distributions/gradle-5.4.1-all.zip
ProjectFolder\android\build.gradle
Update the version of your Android gradle plugin (here we updated to 3.4.0) as Gradle 5 needs a higher one. To get the newer versions you need to add google()
in your repositories. Example of a build.gradle file:
buildscript {
repositories {
google()
}
dependencies {
classpath 'com.android.tools.build:gradle:3.4.0'
}
}
allprojects {
repositories {
google()
mavenLocal()
jcenter()
maven {
url "$rootDir/../node_modules/react-native/android"
}
}
}
ProjectFolder\android\app\build.gradle
This depends on how old your React Native project really is. You need to change your used buildTools, compileSdkVersion, targetSdkVersion and support libaries. Older build.gradle files might look similar to this (Not important parts removed to make the snippet smaller):
...
apply from: "../../node_modules/react-native/react.gradle"
...
android {
compileSdkVersion 28
buildToolsVersion "28.0.3"
defaultConfig {
minSdkVersion 16
targetSdkVersion 28
...
}
...
}
dependencies {
compile "com.android.support:appcompat-v7:28.0.0"
compile "com.facebook.react:react-native:+"
}
...
Dynatrace documentation
The documentation for OneAgent for Android and iOS is available at the following location:
Troubleshooting and current restrictions:
Basically if you have problems with the plugin please have a look into creating logs. They will tell you what went wrong. The logs can be found in the plugins folder of your React Native project (usually node_modules/@dynatrace/react-native-plugin/logs
).
- Currently errors/crashes are reported as errors in the user session and are not visible in the crash overview. This will change in upcoming versions.
- Currently on iOS web requests are not linked with user actions. This is because the actions are currently manual and the web request auto-detected. This will change in upcoming versions.
Missing property DTXApplicationID
means that there is no configuration available. Are you sure you called npm run updateConfiguration
at least once?- Be aware if you change your project to pods when you already have installed the plugin, you will end up with duplicate symbols because of the already linked library. Remove the mdoule reference manually from your project.
Report a bug or open a support case
If you have a problem which can't be solved open a support ticket via Dynatrace (support.dynatrace.com) and provide us the following things:
- Logs from the native agent
- Logs from
node_modules/@dynatrace/react-native-plugin/logs
- Your dynatrace.config.js file
Changelog
0.186.0
- Fixed instrumentation (files were skipped)
- Changed Configuration format
- Android: Switched to JCenter repository
- Applying configuration automatically (>= RN 0.60)
- Updated documenation for manual instrumentation
- Fixed problem with default config and beaconUrl
- Improved text identification of Touchables
- ImageButtons and Icons will now be reported
- Improved logic for plist file insertion
0.182.2
- MacOS: Fixed directory creation issue
0.182.1
- Fixed Typescript Parsing
- Fixed Decorator Parsing
- Fixed directory issue with older node version
0.181.1
- Picker & Swipe to Refresh instrumented
- Dynamic Imports/Requires now supported
- Fixed iOS Bug with reportErrorWithStacktrace
0.179.1
- Made Plugin compatible with RN AutoLinking
- Improved instrumentation of require & imports
- Fixed Button instrumentation
- Improved Text identification of Touchable
- Webrequest linking (Android only)
- Auto User action creation (Android only)
- Report Stacktrace via Error API (Android & iOS)
- Uninstall process now removes everything
- Modifying SourceMap, Debugging now possible
- Fixed configuration issue with npm install
0.174.0
- Switching to new Android instrumentation
- Added options to filter instrumentation
0.172.0
- Error reporting through auto instrumentation
- Debug message output in console
0.171.0
- Added auto instrumentation for React classes
0.168.0