newrelic-react-native-agent
v1.9.1
Published
A New Relic Mobile Agent for React Native
Readme
New Relic React Native Agent
This agent uses native New Relic Android and iOS agents to instrument the React-Native Javascript environment. The New Relic SDKs collect crashes, network traffic, and other information for hybrid apps using native components.
[!IMPORTANT] ⚠️ Breaking change in error reporting (v1.9.0)
Starting with version 1.9.0, JavaScript errors are reported via a new event type:
MobileJSError. They will no longer appear under theMobileHandledExceptionevent type.Action required:
- Alerts: Update your NRQL alert conditions to target
MobileJSError.- Dashboards: Update any custom charts that query
MobileHandledExceptionfor JavaScript-layer errors.- Symbolication: Update your build scripts to the latest version to support source map uploads for this new event. See React Native JavaScript error reporting.
Migrate your NRQL:
- Old query:
SELECT count(*) FROM MobileHandledException WHERE platform = 'reactnative'- New query:
SELECT count(*) FROM MobileJSError
Known Issues
Crash reports may not be sent when ProGuard rules are not properly configured for New Relic in hybrid Android applications.
Symptoms:
- Crashes occur but are not visible in New Relic dashboard
- Crash reporting appears to be non-functional despite correct initialization
Solution: Ensure proper ProGuard rules are added to your ProGuard configuration file. See "Configuring ProGuard Rules" in setup documentation.
Features
- Capture JavaScript errors
- Network Instrumentation
- Distributed Tracing
- Tracking console log, warn and error
- Promise rejection tracking
- Capture interactions and the sequence in which they were created
- Pass user information to New Relic to track user sessions
- Expo Support (Bare Workflow & Managed Workflow)
Current Support:
Android API 24+
iOS:
| Agent Version | Minimum iOS Version | | :--- | :--- | | < 1.5.12 | iOS 10+ | | 1.5.12 – 1.7.0 | iOS 16+ | | >= 1.7.1 | iOS 15+ |
Depends on New Relic iOS/XCFramework and Android agents
Native support levels are based on React Native requirements.
Requirements
- React Native >= 0.61
- IOS native requirements
- Android native requirements
Installation
Yarn
yarn add newrelic-react-native-agentNPM
npm i newrelic-react-native-agentInstalling from a GitHub branch
To try a pre-release feature before it is published to npm, you can install the
agent directly from a branch of this repository. npm and Yarn both support a
github:<owner>/<repo>#<ref> install spec, where <ref> can be a branch name,
tag, or commit SHA.
In your app's package.json, point the dependency at the branch instead of a
version range:
"dependencies": {
"newrelic-react-native-agent": "github:newrelic/newrelic-react-native-agent#feature/reactnative-javascript-error-pipeline"
}Then install:
# npm
npm install
# yarn
yarn installOr add it in one step from the CLI:
# npm
npm i github:newrelic/newrelic-react-native-agent#feature/reactnative-javascript-error-pipeline
# yarn
yarn add newrelic-react-native-agent@github:newrelic/newrelic-react-native-agent#feature/reactnative-javascript-error-pipelineNotes:
- Replace the branch name with whichever branch you want to test. You can also
pin to a tag (
#v1.8.6) or an exact commit SHA (#<commit-sha>) for a reproducible install. - Branch installs resolve to the current tip of that branch. To pull in new
commits after they are pushed, remove the package from
node_modulesand your lockfile entry, then reinstall (e.g.npm install --forceor delete the entry and runnpm install). - After updating the dependency, reinstall pods on iOS
(
cd ios && pod install) and rebuild the app so the native New Relic SDK versions declared in this branch are picked up.
Using a snapshot build of the native Android SDK
Some pre-release branches pin the native New Relic Android agent to a
-SNAPSHOT version (for example 7.7.8-SNAPSHOT). Snapshot artifacts are not
on Maven Central, so you must add the Central Portal Snapshots repository to
your app's android/build.gradle in both the buildscript and
allprojects repository blocks:
buildscript {
repositories {
// ...existing repositories (google(), mavenCentral(), etc.)
maven {
name = "Central Portal Snapshots"
url = "https://central.sonatype.com/repository/maven-snapshots/"
}
}
}
allprojects {
repositories {
// ...existing repositories (google(), mavenCentral(), etc.)
maven {
name = "Central Portal Snapshots"
url = "https://central.sonatype.com/repository/maven-snapshots/"
}
}
}Without this repository, the Android build fails to resolve the snapshot version of the native agent. Once the feature ships to a stable release, you can remove the snapshots repository.
React Native Setup
Now open your index.js and add the following code to launch NewRelic (don't forget to put proper application tokens):
import NewRelic from 'newrelic-react-native-agent';
import * as appVersion from './package.json';
import {Platform} from 'react-native';
let appToken;
if (Platform.OS === 'ios') {
appToken = '<IOS-APP-TOKEN>';
} else {
appToken = '<ANDROID-APP-TOKEN>';
}
const agentConfiguration = {
//Android Specific
// Optional:Enable or disable collection of event data.
analyticsEventEnabled: true,
//Android Specific
// Optional:Enable or disable collection of native c/c++ crash.
nativeCrashReportingEnabled: false,
// Optional:Enable or disable crash reporting.
crashReportingEnabled: true,
// Optional:Enable or disable interaction tracing. Trace instrumentation still occurs, but no traces are harvested. This will disable default and custom interactions.
interactionTracingEnabled: false,
// Optional:Enable or disable reporting successful HTTP requests to the MobileRequest event type.
networkRequestEnabled: true,
// Optional:Enable or disable reporting network and HTTP request errors to the MobileRequestError event type.
networkErrorRequestEnabled: true,
// Optional:Enable or disable capture of HTTP response bodies for HTTP error traces, and MobileRequestError events.
httpResponseBodyCaptureEnabled: true,
// Optional:Enable or disable agent logging.
loggingEnabled: true,
// Optional:Specifies the log level. Omit this field for the default log level.
// Options include: ERROR (least verbose), WARNING, INFO, VERBOSE, AUDIT (most verbose).
logLevel: NewRelic.LogLevel.INFO,
// iOS Specific
// Optional:Enable/Disable automatic instrumentation of WebViews
webViewInstrumentation: true,
// Optional:Set a specific collector address for sending data. Omit this field for default address.
//collectorAddress: "",
// Optional:Set a specific crash collector address for sending crashes. Omit this field for default address.
//crashCollectorAddress: "",
// Optional:Enable or disable reporting data using different endpoints for US government clients.
//fedRampEnabled: false
// Optional: Enable or disable offline data storage when no internet connection is available.
offlineStorageEnabled:true,
// iOS Specific
// Optional: Enable or disable Background Reporting.
backgroundReportingEnabled:false,
// iOS Specific
// Optional: Enable or disable to use our new, more stable, event system for iOS agent.
newEventSystemEnabled:false,
// Optional: Enable or disable distributed tracing.
distributedTracingEnabled: true,
// Optional: Enable or disable collection of JavaScript errors reported via recordError
// (routed through the MobileJSError / /mobile/errors protocol). Enabled by default.
jsErrorReportingEnabled: true,
};
NewRelic.startAgent(appToken,agentConfiguration);
NewRelic.setJSAppVersion(appVersion.version);
AppRegistry.registerComponent(appName, () => App);
AppToken is platform-specific. You need to generate the seprate token for Android and iOS apps.
Android Setup
Install the New Relic native Android agent (instructions here).
Add the following changes to Apply Gradle Plugin:
If you are using Plugins DSL to Apply the NewRelic Gradle Plugin, make the following changes:
In android/settings.gradle:
plugins {
id "com.android.application" version "7.4.2" apply false
id "org.jetbrains.kotlin.android" version "1.7.10" apply false
id "com.newrelic.agent.android" version "7.8.2" apply false // <-- include this
}In android/app/build.gradle:
plugins {
id "com.android.application"
id "kotlin-android"
id "com.newrelic.agent.android" //<-- include this
}Or, if you are using the traditional way to apply the plugin:
buildscript {
...
repositories {
...
mavenCentral()
}
dependencies {
...
classpath "com.newrelic.agent.android:agent-gradle-plugin:7.8.2"
}
}Apply the NewRelic plugin to the top of the android/app/build.gradle file:
apply plugin: "com.android.application"
apply plugin: 'newrelic' // <-- include thisiOS Setup
Run the following, and it will install the New Relic XCFramework agent:
npx pod-installiOS package manager: CocoaPods (default) or Swift Package Manager (opt-in)
By default the agent is consumed via the NewRelicAgent CocoaPods spec, which works on every supported React Native version (>= 0.61).
Consumers on React Native 0.75+ can opt-in to fetch the underlying NewRelic iOS agent via Swift Package Manager (from newrelic/newrelic-ios-agent-spm) instead. This anticipates CocoaPods moving to read-only and aligns with apps that already integrate other iOS dependencies through SPM.
Requirements for the SPM path:
- React Native >= 0.75 (the SPM helper ships in
react-native/scripts/cocoapods/spm.rb). - The consumer Podfile must use
use_frameworks! :linkage => :dynamic. Mixing static linkage with SPM produces linker errors. - The consumer Podfile must call
react_native_post_install(installer, ...)in itspost_installblock (this is the default in the standard RN template; that's where the SPM packages are wired into the generated Xcode project).
Enabling SPM — in your app's ios/Podfile, add at the top:
ENV['NEWRELIC_USE_SPM'] = '1'
use_frameworks! :linkage => :dynamicThen run pod install. After install, Pods/Pods.xcodeproj will reference the newrelic-ios-agent-spm package, and Podfile.lock will no longer list NewRelicAgent.
Troubleshooting:
- Duplicate symbol errors mentioning
_NewRelic...— the project is mixing static linkage with SPM. Confirmuse_frameworks! :linkage => :dynamicis set, thenpod deintegrate && pod install. - "package requires tvOS 15" — bump your iOS app's tvOS deployment target. The SPM package and
NewRelicAgentitself both require tvOS 15+. - "Swift package not found" during build — close and reopen the Xcode workspace after
pod installto let Xcode resolve the package graph.
AutoLinking and rebuilding
- Once the above steps have been completed, the React Native NewRelic library must be linked to your project and your application needs to be rebuilt. If you use React Native 0.60+, you automatically have access to "autolinking," requiring no further manual installation steps.
To automatically link the package, rebuild your project:
# Android apps
npx react-native run-android
# iOS apps
cd ios/
pod install --repo-update
cd ..
npx react-native run-iosIf you run following commands then Fatal JS erros will show up as a crash in NR.
npx react-native run-ios --mode=release
npx react-native run-android --mode=release
Expo
Integration with Expo is possible in both bare workflow and custom managed workflow via config plugins.
- Bare Workflow:
- Please follow the above installation steps instead.
- Managed Workflow:
- Install our package by running
npx expo install newrelic-react-native-agent. You should see the plugin inapp.jsonorapp.config.js:
{ "name": "my app", "plugins": ["newrelic-react-native-agent"] }- Update
index.jswith the configurations steps above. - After this, you need to use the
expo prebuild --cleancommand as described in the "Adding custom native code" guide to rebuild your app with the plugin changes. If this command is not running, you'll get errors when starting the New Relic agent. - For Expo Go users, the agent will require using native code. Since Expo Go does not suport sending custom native code over-the-air, you can follow Expo's documentation on how to use "Custom native code in Expo Go".
- Install our package by running
Automatic Android source map / mapping file upload (Expo)
Since android/ is regenerated on every expo prebuild (locally and on EAS Build), the
plugin can write android/app/newrelic.properties for you on each prebuild, sourcing
your New Relic User API key
and your Android application token
(the same one passed to NewRelic.startAgent()) from environment variables instead of
committing them to the repo. Both values are required — the agent's
newrelicReactNativeSourceMapUploadRelease and newrelicMapUploadRelease Gradle tasks
read com.newrelic.api_key and com.newrelic.application_token from this file to
authenticate the upload of the React Native source map and ProGuard/R8 mapping file
after release builds — see React Native JavaScript error reporting.
By default the plugin reads the User API key from NEWRELIC_USER_API_KEY and the
application token from NEWRELIC_ANDROID_APP_TOKEN:
{
"name": "my app",
"plugins": ["newrelic-react-native-agent"]
}To use different environment variable names, pass them explicitly:
{
"name": "my app",
"plugins": [
[
"newrelic-react-native-agent",
{
"android": {
"apiKeyEnvName": "MY_NR_USER_API_KEY",
"appTokenEnvName": "MY_NR_ANDROID_APP_TOKEN"
}
}
]
]
}If only one of the two variables is set, the plugin still writes that single property; the Gradle task then logs which one is missing rather than failing the build. Set the variables for your build:
- EAS Build: store both as EAS environment variables with
--visibility plaintextor--visibility sensitive(e.g.eas env:set --environment production --name NEWRELIC_USER_API_KEY --value <value> --visibility sensitiveand the equivalent forNEWRELIC_ANDROID_APP_TOKEN), scoped to the environments you build with. Do not use--visibility secret— secret-visibility variables are reserved for EAS's own credential system and are never exposed asprocess.envto build scripts, so the plugin won't see them and will silently skip writingnewrelic.properties. EAS Build resolves plaintext/sensitive variables before runningprebuild, whether the build runs on EAS's servers or locally witheas build --local. - Bare
expo prebuild/expo run:android: export both variables in your shell, or add them to a.envfile loaded by your tooling, before running the build.
If neither environment variable is set, the plugin leaves newrelic.properties untouched and the two Gradle tasks skip the upload with a log message rather than failing the build.
Automatic iOS dSYM / source map upload (Expo)
Unlike Android, the dSYM and React Native source map upload scripts
(run-symbol-tool and upload-react-native-sourcemap, from the
dsym-upload-tools
folder) don't ship inside the NewRelicAgent CocoaPod, and the Run Script build phase
that invokes them normally has to be added by hand in Xcode — which doesn't survive
expo prebuild regenerating ios/ from scratch. The plugin vendors both scripts and,
on every prebuild:
- Copies them into
ios/dsym-upload-tools. - Adds a Run Script build phase (after "Bundle React Native code and images") that runs both scripts, reading credentials from environment variables — never written to any generated file, only referenced by name in the build phase's shell script.
- Ensures the "Bundle React Native code and images" phase exports
SOURCEMAP_FILE, since Expo's default template doesn't set it and the source map won't be generated otherwise.
By default the build phase reads the iOS application token from NEWRELIC_IOS_APP_TOKEN
and the User/Ingest API key from NEWRELIC_USER_API_KEY (shared with the Android
default — same key type, get one here):
{
"name": "my app",
"plugins": ["newrelic-react-native-agent"]
}To use different environment variable names, pass them explicitly:
{
"name": "my app",
"plugins": [
[
"newrelic-react-native-agent",
{
"ios": {
"appTokenEnvName": "MY_NR_IOS_APP_TOKEN",
"apiKeyEnvName": "MY_NR_USER_API_KEY"
}
}
]
]
}Set the variables for your build the same way as the Android ones above (EAS environment
variables with plaintext/sensitive visibility, or exported in your shell for bare
expo prebuild / expo run:ios). If a variable is missing at build time, the phase logs
which one and skips that upload rather than failing the build. Both underlying scripts
also skip automatically for non-Release configurations and for simulator builds (the
source map script has a NEWRELIC_SOURCEMAP_ALLOW_SIMULATOR=true escape hatch for
testing the upload path on a simulator).
Routing Instrumentation
We currently provide two routing instrumentations out of the box to instrument route changes for and route changes record as Breadcrumb.
v5 set the
onStateChangetoNewRelic.onStateChangein your NavigationContainer as follows:<NavigationContainer onStateChange={ NewRelic.onStateChange } /><=v4 set the
onNavigationStateChangetoNewRelic.onNavigationStateChangein your App wrapper as follows:export default () => ( <App onNavigationStateChange={ NewRelic.onNavigationStateChange } /> );
Register
NewRelic.componentDidAppearListenerlistener using:Navigation.events().registerComponentDidAppearListener( NewRelic.componentDidAppearListener );
Alternatively, you can report your screen changes manually using the following API:
var params = {
'screenName':'screenName'
};
NewRelic.recordBreadcrumb('navigation',params);
Usage
See the examples below, and for more detail, see New Relic IOS SDK doc or Android SDK.
startInteraction(interactionName: string): Promise<InteractionId>;
Track a method as an interaction.
InteractionId is string.
setInteractionName(interactionName: string): void;
Name or rename interaction (Android-specific).
endInteraction(id: InteractionId): void;
End an interaction (Required). This uses the string ID for the interaction you want to end. This string is returned when you use startInteraction().
const badApiLoad = async () => {
const interactionId = await NewRelic.startInteraction('StartLoadBadApiCall');
console.log(interactionId);
const url = 'https://facebook.github.io/react-native/moviessssssssss.json';
fetch(url)
.then((response) => response.json())
.then((responseJson) => {
console.log(responseJson);
NewRelic.endInteraction(interactionId);
}) .catch((error) => {
NewRelic.endInteraction(interactionId);
console.error(error);
});;
};
setAttribute(name: string, value: boolean | number | string): void;
Creates a session-level attribute shared by multiple mobile event types. Overwrites its previous value and type each time it is called.
NewRelic.setAttribute('RNCustomAttrNumber', 37);removeAttribute(name: string, value: boolean | number | string): void;
This method removes the attribute specified by the name string..
NewRelic.removeAttribute('RNCustomAttrNumber');incrementAttribute(name: string, value?: number): void;
Increments the count of an attribute with a specified name. Overwrites its previous value and type each time it is called. If the attribute does not exists, it creates a new attribute. If no value is given, it increments the value by 1.
NewRelic.incrementAttribute('RNCustomAttrNumber');
NewRelic.incrementAttribute('RNCustomAttrNumber', 5);setUserId(userId: string): void;
Set a custom user identifier value to associate user sessions with analytics events and attributes.
NewRelic.setUserId("RN12934");recordBreadcrumb(name: string, attributes?: {[key: string]: any}): void;
Track app activity/screen that may be helpful for troubleshooting crashes.
NewRelic.recordBreadcrumb("shoe", {"shoeColor": "blue","shoesize": 9,"shoeLaces": true});recordCustomEvent(eventType: string, eventName?: string, attributes?: {[key: string]: any}): void;
Creates and records a custom event for use in New Relic Insights.
NewRelic.recordCustomEvent("mobileClothes", "pants", {"pantsColor": "blue","pantssize": 32,"belt": true});crashNow(message?: string): void;
Throws a demo run-time exception to test New Relic crash reporting.
NewRelic.crashNow();
NewRelic.crashNow("New Relic example crash message");currentSessionId(): Promise;
Returns the current session ID. This method is useful for consolidating monitoring of app data (not just New Relic data) based on a single session definition and identifier.
let sessionId = await NewRelic.currentSessionId();noticeHttpTransaction(url: string, httpMethod: string, statusCode: number, startTime: number, endTime: number, bytesSent: number, bytesReceived: number, responseBody: string): void;
Tracks network requests manually. You can use this method to record HTTP transactions, with an option to also send a response body.
NewRelic.noticeHttpTransaction('https://github.com', 'GET', 200, Date.now(), Date.now()+1000, 100, 101, "response body");noticeNetworkFailure(url: string, httpMethod: string, startTime: number, endTime: number, failure: string): void;
Records network failures. If a network request fails, use this method to record details about the failures. In most cases, place this call inside exception handlers, such as catch blocks.
NewRelic.noticeNetworkFailure('https://github.com', 'GET', Date.now(), Date.now(), NewRelic.NetworkFailure.BadURL);recordMetric(name: string, category: string, value?: number, countUnit?: string, valueUnit?: string): void;
Records custom metrics (arbitrary numerical data), where countUnit is the measurement unit of the metric count and valueUnit is the measurement unit for the metric value. If using countUnit or valueUnit, then all of value, countUnit, and valueUnit must all be set.
NewRelic.recordMetric('RNCustomMetricName', 'RNCustomMetricCategory');
NewRelic.recordMetric('RNCustomMetricName', 'RNCustomMetricCategory', 12);
NewRelic.recordMetric('RNCustomMetricName', 'RNCustomMetricCategory', 13, NewRelic.MetricUnit.PERCENT, NewRelic.MetricUnit.SECONDS);removeAllAttributes(): void;
Removes all attributes from the session
NewRelic.removeAllAttributes();recordError(e: string|error, isFatal?: boolean, attributes?: {[key: string]: any}): void;
Records JavaScript errors for react-native.
e(required): A JavaScriptErrorobject or an error message string.isFatal(optional, defaultfalse): Marks the error as fatal. Fatal errors are reported as crashes; non-fatal errors are reported as handled exceptions.attributes(optional, default{}): A key/value map of custom attributes attached to the recorded error. Values may be strings, numbers, or booleans.Errors are routed through the
MobileJSError//mobile/errorsprotocol and can be disabled with thejsErrorReportingEnabledagent configuration flag.
try {
var foo = {};
foo.bar();
} catch(e) {
NewRelic.recordError(e);
}You can also flag an error as fatal and attach custom attributes:
try {
var foo = {};
foo.bar();
} catch(e) {
NewRelic.recordError(e, false, {
'screen': 'Checkout',
'cartItemCount': 3,
'isGuestCheckout': true,
});
}setMaxEventBufferTime(maxBufferTimeInSeconds: number): void;
Sets the event harvest cycle length. Default is 600 seconds (10 minutes). Minimum value can not be less than 60 seconds. Maximum value should not be greater than 600 seconds.
NewRelic.setMaxEventBufferTime(60);setMaxEventPoolSize(maxSize: number): void;
Sets the maximum size of the event pool stored in memory until the next harvest cycle. Default is a maximum of 1000 events per event harvest cycle. When the pool size limit is reached, the agent will start sampling events, discarding some new and old, until the pool of events is sent in the next harvest cycle.
NewRelic.setMaxEventPoolSize(2000);The following methods allow you to set some agent configurations after the agent has started:
Follow these steps if the agent has not started yet.
analyticsEventEnabled(enabled: boolean) : void;
FOR ANDROID ONLY. Enable or disable the collecton of event data.
NewRelic.analyticsEventEnabled(true);networkRequestEnabled(enabled: boolean) : void;
Enable or disable reporting successful HTTP requests to the MobileRequest event type.
NewRelic.networkRequestEnabled(true);networkErrorRequestEnabled(enabled: boolean) : void;
Enable or disable reporting network and HTTP request errors to the MobileRequestError event type.
NewRelic.networkErrorRequestEnabled(true);httpResponseBodyCaptureEnabled(enabled: boolean) : void;
Enable or disable capture of HTTP response bodies for HTTP error traces, and MobileRequestError events.
NewRelic.httpResponseBodyCaptureEnabled(true);shutdown() : void;
Shut down the agent within the current application lifecycle during runtime.
NewRelic.shutdown();recordReplay(): void;
Start recording session replay. Call this method to manually start capturing session replay data after it has been paused or if auto-start is disabled. Session replay captures user interactions and screen recordings for playback in New Relic One.
NewRelic.recordReplay();pauseReplay(): void;
Pause the session replay recording. Use this method to temporarily stop capturing session replay data without ending the session. Recording can be resumed by calling
recordReplay().
NewRelic.pauseReplay();addHTTPHeadersTrackingFor() : void;
This API allows you to add any header field strings to a list that gets recorded as attributes with networking request events. After header fields have been added using this function, if the headers are in a network call they will be included in networking events in NR1.
NewRelic.addHTTPHeadersTrackingFor(["Car","Music"]);setMaxOfflineStorageSize() : void;
Sets the maximum size of total data that can be stored for offline storage.By default, mobile monitoring can collect a maximum of 100 megaBytes of offline storage. When a data payload fails to send because the device doesn't have an internet connection, it can be stored in the file system until an internet connection has been made. After a typical harvest payload has been successfully sent, all offline data is sent to New Relic and cleared from storage.
NewRelic.setMaxOfflineStorageSize(200);logInfo(String message) : void
Logs an informational message to the New Relic log.
NewRelic.logInfo();logError(String message) : void
Logs an error message to the New Relic log.
NewRelic.logError("This is an error message");logVerbose(String message) : void
Logs a verbose message to the New Relic log.
NewRelic.logVerbose("This is a verbose message");logWarning(String message) : void
Logs a warning message to the New Relic log.
NewRelic.logWarning("This is a warning message");logDebug(String message) : void
Logs a debug message to the New Relic log.
NewRelic.logDebug("This is a debug message");log(LogLevel level, String message) : void
Logs a message to the New Relic log with a specified log level.
NewRelic.log(LogLevel.INFO, "This is an informational message");logAll(Error error,attributes?: {[key: string]: any}) : void
Logs an exception with attributes to the New Relic log.
Newrelic.logAll(new Error("This is an exception"),
{"BreadNumValue": 12.3 ,
"BreadStrValue": "FlutterBread",
"BreadBoolValue": true ,
"message": "This is a message with attributes" }
);logAttributes(attributes?: {[key: string]: any}) : void
Logs a message with attributes to the New Relic log.
Newrelic.logAttributes(
{"BreadNumValue": 12.3 ,
"BreadStrValue": "FlutterBread",
"BreadBoolValue": true ,
"message": "This is a message with attributes",
level:newRelic.LogLevel.INFO });How to see JSErrors(Fatal/Non Fatal) in NewRelic One?
React Native Agent v1.9.0 and above:
JavaScript errors and promise rejections are recorded as MobileJSError events. You will be able to see the event trail, attributes, and stack trace for each JavaScript error in New Relic One.
You can also find these errors by running this query:
SELECT * FROM MobileJSError SINCE 24 hours agoJavaScript error reporting is enabled by default. To disable it, set the
jsErrorReportingEnabled feature flag to false in the agent configuration
passed to startAgent:
const agentConfiguration = {
// ...other options
// Enable or disable collection of JavaScript errors reported via recordError
// (routed through the MobileJSError / /mobile/errors protocol). Enabled by default.
jsErrorReportingEnabled: false,
};To make the stack traces in MobileJSError events human-readable, upload the source map for your JavaScript bundle. See React Native JavaScript error reporting for automatic and manual source map upload (including CodePush/OTA updates), the upload API reference, and troubleshooting.
React Native Agent v1.2.0 to v1.8.x:
JavaScript errors and promise rejections can be seen in the Handled Exceptions tab in New Relic One. You will be able to see the event trail, attributes, and stack trace for each JavaScript error recorded.
You can also build a dashboard for these errors using this query:
SELECT * FROM MobileHandledException SINCE 24 hours agoReact Native Agent v1.1.0 and below:
There is no section for JavaScript errors, but you can see JavaScript errors in custom events and also query them in NRQL explorer.
You can also build dashboard for errors using this query:
SELECT jsAppVersion,name,Message,errorStack,isFatal FROM `JS Errors` SINCE 24 hours agoSymbolicating a stack trace
The agent symbolicates JavaScript errors by uploading the source map for your JavaScript bundle, so the stack traces in MobileJSError events are human-readable. The agent can upload source maps automatically after each build, and you can also upload them manually (including for CodePush/OTA updates). For full setup, the upload API reference, and troubleshooting, see React Native JavaScript error reporting.
If you prefer to symbolicate a release build's stack trace manually, follow the steps described here for Symbolication.
* IMPORTANT considerations and best practices include:
*
* - You should limit the total number of event types to approximately five.
* eventType is meant to be used for high-level categories.
* For example, you might create an event type Gestures.
*
* - Do not use eventType to name your custom events.
* Create an attribute to name an event or use the optional name parameter.
* You can create many custom events; it is only event types that you should limit.
*
* - Using the optional name parameter has the same effect as adding a name key in the attributes dictionary.
* name is a keyword used for displaying your events in the New Relic UI.
* To create a useful name, you might combine several attributes.Uploading dSYM files
Our iOS agent includes a Swift script intended to be run from a build script in your target's build phases in XCode. The script automatically uploads dSYM files in the background (or converts your dSYM to the New Relic map file format), and then performs a background upload of the files needed for crash symbolication to New Relic.
To invoke this script during an XCode build:
- Copy the dsym-upload-tools folder from this repository: https://github.com/newrelic/newrelic-ios-agent-spm, to your projects SRCROOT folder first.
- In Xcode, select your project in the navigator, then click on the application target.
- Select the Build Phases tab in the settings editor.
- Click the + icon above Target Dependencies and choose New Run Script Build Phase. Ensure the new build script is the very last build script.
- Add the following lines of code to the new phase and replace
APP_TOKENwith your iOS application token.- If there is a checkbox below Run script that says "Run script: Based on Dependency analysis" please make sure it is not checked.
React Native agent 1.3.1 or higher
With the ios agent 7.4.6 release, the XCFramework no longer includes the dsym-upload-tools. You can find the dsym-upload-tools in the dsym-upload-tools folder of the https://github.com/newrelic/newrelic-ios-agent-spm Swift Package Manager repository. Please copy the dsym-upload-tools directory into your application source code directory by copying the XCFramework into your project or using Cocoapods if you're integrating the New Relic iOS Agent. Use the run script below in your Xcode build phases to perform symbol upload steps during app builds in Xcode.
ARTIFACT_DIR="${BUILD_DIR%Build/*}"
SCRIPT=`/usr/bin/find "${SRCROOT}" "${ARTIFACT_DIR}" -type f -name run-symbol-tool | head -n 1`
/bin/sh "${SCRIPT}" "APP_TOKEN"React Native agent 0.0.8 or higher
ARTIFACT_DIR="${BUILD_DIR%Build/*}"
SCRIPT=`/usr/bin/find "${SRCROOT}" "${ARTIFACT_DIR}" -type f -name run-symbol-tool | head -n 1`
/bin/sh "${SCRIPT}" "APP_TOKEN"React Native agent 0.0.7 or lower
SCRIPT=`/usr/bin/find "${SRCROOT}" -name newrelic_postbuild.sh | head -n 1`
if [ -z "${SCRIPT}"]; then
ARTIFACT_DIR="${BUILD_DIR%Build/*}SourcePackages/artifacts"
SCRIPT=`/usr/bin/find "${ARTIFACT_DIR}" -name newrelic_postbuild.sh | head -n 1`
fi
/bin/sh "${SCRIPT}" "APP_TOKEN"Note: The automatic script requires bitcode to be disabled. You should clean and rebuild your app after adding the script.
Missing dSYMs
The automatic script will create an upload_dsym_results.log file in your project's iOS directory, which contains information about any failures that occur during symbol upload.
If dSYM files are missing, you may need to check Xcode build settings to ensure the file is being generated. Frameworks which are built locally have separate build settings and may need to be updated as well.
Build settings:
Debug Information Format : Dwarf with dSYM File
Deployment Postprocessing: Yes
Strip Linked Product: Yes
Strip Debug Symbols During Copy : YesIf you're using Expo, the config plugin can vendor these scripts and add the Run Script build phase for you automatically on every prebuild — see Automatic iOS dSYM / source map upload (Expo).
Configure app launch times
To measure app launch time, you can refer to the following documentation for both Android and iOS platforms.
Known Issues
Crash reports may not be sent when ProGuard rules are not properly configured for New Relic in hybrid Android applications.
Solution: Ensure proper ProGuard rules are added to your ProGuard configuration file. See Configuring ProGuard Rules in setup documentation.
Testing
Jest Configuration
By default, node_modules are ignored by transformers by Jest. To configure the newrelic-react-native-agent to work with Jest, you should add this package to transformIgnorePatterns. We also provide some basic mocks for our API calls in jestSetup.js. Simply add this file to setupFiles in your Jest configuration. An example jest configuration would look like:
"jest": {
"preset": "react-native",
"transformIgnorePatterns": [
"node_modules/(?!@react-native|react-native|newrelic-react-native-agent)"
],
"setupFiles": [
"./node_modules/newrelic-react-native-agent/jestSetup.js"
]
}
