### Install and Run iOS App Source: https://github.com/newrelic/newrelic-react-native-agent/blob/main/README.md Commands to install dependencies and run the iOS application. ```shell cd ios/ pod install --repo-update cd .. npx react-native run-ios ``` -------------------------------- ### Install Dependencies and Run Tests Source: https://github.com/newrelic/newrelic-react-native-agent/blob/main/CONTRIBUTING.md Use these commands to install project dependencies and run the test suite. Ensure all dependencies are removed before building. ```bash npm install npm test ``` -------------------------------- ### Install and Initialize New Relic Agent Source: https://context7.com/newrelic/newrelic-react-native-agent/llms.txt Install the agent via npm or Yarn and initialize it at the top of your index.js file before registering the app component. Configure various agent settings such as crash reporting, network requests, and logging levels. ```javascript // yarn add newrelic-react-native-agent // npm i newrelic-react-native-agent // index.js import NewRelic from 'newrelic-react-native-agent'; import * as appVersion from './package.json'; import { AppRegistry, Platform } from 'react-native'; import App from './App'; import { name as appName } from './app.json'; const appToken = Platform.OS === 'ios' ? '' : ''; const agentConfiguration = { analyticsEventEnabled: true, // Android: collect event data nativeCrashReportingEnabled: false, // Android: collect native C/C++ crashes crashReportingEnabled: true, // capture JS crashes interactionTracingEnabled: false, // harvest interaction traces networkRequestEnabled: true, // report successful HTTP requests networkErrorRequestEnabled: true, // report HTTP errors httpResponseBodyCaptureEnabled: true, // capture HTTP error response bodies loggingEnabled: true, logLevel: NewRelic.LogLevel.INFO, // ERROR | WARN | INFO | VERBOSE | AUDIT | DEBUG webViewInstrumentation: true, // iOS: auto-instrument WebViews collectorAddress: '', // optional custom collector endpoint crashCollectorAddress: '', // optional custom crash endpoint fedRampEnabled: false, // US Gov FedRAMP endpoints offlineStorageEnabled: true, // buffer data while offline backgroundReportingEnabled: false, // iOS: background reporting newEventSystemEnabled: false, // iOS: new event system distributedTracingEnabled: true, }; NewRelic.startAgent(appToken, agentConfiguration); NewRelic.setJSAppVersion(appVersion.version); AppRegistry.registerComponent(appName, () => App); ``` -------------------------------- ### Install New Relic iOS Agent Source: https://github.com/newrelic/newrelic-react-native-agent/blob/main/README.md Use `npx pod-install` to install the New Relic XCFramework agent for iOS applications. ```shell npx pod-install ``` -------------------------------- ### recordReplay Source: https://github.com/newrelic/newrelic-react-native-agent/blob/main/README.md 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. ```APIDOC ## recordReplay(): void; ### Description Starts recording session replay data. ### Method `recordReplay` ### Request Example ```javascript NewRelic.recordReplay(); ``` ``` -------------------------------- ### Track API Call as Interaction Source: https://github.com/newrelic/newrelic-react-native-agent/blob/main/README.md Example of tracking an asynchronous API call as a New Relic interaction. It starts an interaction, fetches data, and ends the interaction, handling potential errors. ```javascript 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); });; }; ``` -------------------------------- ### Jest Testing Setup Source: https://context7.com/newrelic/newrelic-react-native-agent/llms.txt Configure Jest in `package.json` to use the provided `jestSetup.js` file, which mocks all agent APIs to prevent native module errors during unit tests. Ensure `newrelic-react-native-agent` is included in `transformIgnorePatterns`. ```json // package.json (jest section) { "jest": { "preset": "react-native", "transformIgnorePatterns": [ "node_modules/(?!@react-native|react-native|newrelic-react-native-agent)" ], "setupFiles": [ "./node_modules/newrelic-react-native-agent/jestSetup.js" ] } } ``` ```javascript // Your test file — all NewRelic calls are auto-mocked import NewRelic from 'newrelic-react-native-agent'; import { render, fireEvent } from '@testing-library/react-native'; import CheckoutScreen from '../screens/CheckoutScreen'; test('records custom event on purchase', () => { const { getByText } = render(); fireEvent.press(getByText('Buy Now')); expect(NewRelic.recordCustomEvent).toHaveBeenCalledWith( 'UserAction', 'ProductPurchased', expect.objectContaining({ productId: expect.any(String) }) ); }); ``` -------------------------------- ### Start Session Replay Recording Source: https://github.com/newrelic/newrelic-react-native-agent/blob/main/README.md Manually initiates the capture of session replay data, including user interactions and screen recordings, for playback in New Relic One. Use this after pausing or if auto-start is disabled. ```javascript NewRelic.recordReplay(); ``` -------------------------------- ### Rebuild Android App Source: https://github.com/newrelic/newrelic-react-native-agent/blob/main/README.md After completing the setup steps, rebuild your Android application using `npx react-native run-android` to link the New Relic library. ```shell npx react-native run-android ``` -------------------------------- ### Control Session Replay Recording Source: https://context7.com/newrelic/newrelic-react-native-agent/llms.txt Manually start, resume, or temporarily pause session replay recording. Use `pauseReplay()` for screens with sensitive content. ```javascript import NewRelic from 'newrelic-react-native-agent'; // Pause replay on screens with sensitive content function onNavigateToPrivateNotes() { NewRelic.pauseReplay(); } // Resume replay when returning to safe screens function onNavigateToFeed() { NewRelic.recordReplay(); } ``` -------------------------------- ### Install New Relic React Native Agent with NPM Source: https://github.com/newrelic/newrelic-react-native-agent/blob/main/README.md Use this command to add the New Relic React Native Agent to your project dependencies when using NPM. ```sh npm i newrelic-react-native-agent ``` -------------------------------- ### Install New Relic React Native Agent with Yarn Source: https://github.com/newrelic/newrelic-react-native-agent/blob/main/README.md Use this command to add the New Relic React Native Agent to your project dependencies when using Yarn. ```sh yarn add newrelic-react-native-agent ``` -------------------------------- ### Session Replay Control Source: https://context7.com/newrelic/newrelic-react-native-agent/llms.txt Controls session replay recording. Allows manually starting, resuming, or temporarily pausing capture without ending the session. ```APIDOC ## `recordReplay()` / `pauseReplay()` Controls session replay recording. Call `recordReplay()` to manually start or resume capture; call `pauseReplay()` to temporarily stop it without ending the session. ### Example ```js import NewRelic from 'newrelic-react-native-agent'; // Pause replay on screens with sensitive content function onNavigateToPrivateNotes() { NewRelic.pauseReplay(); } // Resume replay when returning to safe screens function onNavigateToFeed() { NewRelic.recordReplay(); } ``` ``` -------------------------------- ### Start, End, and Set Interaction Names Source: https://context7.com/newrelic/newrelic-react-native-agent/llms.txt Wraps code segments as New Relic Interaction traces. `startInteraction` returns an interaction ID for `endInteraction`. `setInteractionName` renames the active interaction (Android only). ```javascript import NewRelic from 'newrelic-react-native-agent'; async function loadProductCatalog() { const interactionId = await NewRelic.startInteraction('LoadProductCatalog'); try { const res = await fetch('https://api.example.com/products'); const data = await res.json(); return data; } catch (e) { NewRelic.recordError(e); return []; } finally { NewRelic.endInteraction(interactionId); } } ``` ```javascript // Android only: rename the running interaction async function doComplexWork() { const id = await NewRelic.startInteraction('InitialName'); NewRelic.setInteractionName('RenamedInteraction'); // ... work ... NewRelic.endInteraction(id); } ``` -------------------------------- ### addHTTPHeadersTrackingFor Source: https://github.com/newrelic/newrelic-react-native-agent/blob/main/README.md 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. ```APIDOC ## addHTTPHeadersTrackingFor(headers: string[]): void; ### Description Adds specified HTTP headers to be tracked with networking request events. ### Method `addHTTPHeadersTrackingFor` ### Parameters #### Path Parameters - **headers** (string[]) - Required - An array of header field strings to track. ### Request Example ```javascript NewRelic.addHTTPHeadersTrackingFor(["Car","Music"]); ``` ``` -------------------------------- ### startAgent Source: https://context7.com/newrelic/newrelic-react-native-agent/llms.txt Initialises the native New Relic agent, hooks into error handlers, and overrides console methods. This must be called once before any other API. ```APIDOC ## startAgent(appkey, customerConfiguration) ### Description Initialises the native New Relic agent, hooks into the global JS error handler, unhandled promise rejection tracker, and overrides `console.*`. Must be called once, before any other API. ### Method `NewRelic.startAgent` ### Parameters - **appkey** (string) - Required - The application token for New Relic. - **customerConfiguration** (object) - Optional - Configuration object for the agent. - **analyticsEventEnabled** (boolean) - Android: collect event data. - **nativeCrashReportingEnabled** (boolean) - Android: collect native C/C++ crashes. - **crashReportingEnabled** (boolean) - capture JS crashes. - **interactionTracingEnabled** (boolean) - harvest interaction traces. - **networkRequestEnabled** (boolean) - report successful HTTP requests. - **networkErrorRequestEnabled** (boolean) - report HTTP errors. - **httpResponseBodyCaptureEnabled** (boolean) - capture HTTP error response bodies. - **loggingEnabled** (boolean) - enable logging. - **logLevel** (NewRelic.LogLevel) - Set the logging level (e.g., `NewRelic.LogLevel.INFO`). - **webViewInstrumentation** (boolean) - iOS: auto-instrument WebViews. - **collectorAddress** (string) - optional custom collector endpoint. - **crashCollectorAddress** (string) - optional custom crash endpoint. - **fedRampEnabled** (boolean) - US Gov FedRAMP endpoints. - **offlineStorageEnabled** (boolean) - buffer data while offline. - **backgroundReportingEnabled** (boolean) - iOS: background reporting. - **newEventSystemEnabled** (boolean) - iOS: new event system. - **distributedTracingEnabled** (boolean) - enable distributed tracing. ### Request Example ```javascript import NewRelic from 'newrelic-react-native-agent'; import { Platform } from 'react-native'; NewRelic.startAgent( Platform.OS === 'ios' ? 'IOS_APP_TOKEN' : 'ANDROID_APP_TOKEN', { crashReportingEnabled: true, networkRequestEnabled: true, logLevel: NewRelic.LogLevel.VERBOSE, offlineStorageEnabled: true, distributedTracingEnabled: true, } ); ``` ``` -------------------------------- ### endInteraction Source: https://github.com/newrelic/newrelic-react-native-agent/blob/main/README.md End an interaction using its ID. This is a required step after starting an interaction. ```APIDOC ## endInteraction ### Description End an interaction using its unique string ID. This is required to complete the interaction tracking. ### Method Signature `endInteraction(id: InteractionId): void;` ### Parameters * **id** (InteractionId) - The string ID of the interaction to end, typically obtained from `startInteraction()`. ### Example ```javascript NewRelic.endInteraction(interactionId); ``` ``` -------------------------------- ### startInteraction Source: https://github.com/newrelic/newrelic-react-native-agent/blob/main/README.md Track a method as an interaction. This is useful for measuring the duration of specific operations. ```APIDOC ## startInteraction ### Description Track a method as an interaction. Returns a Promise that resolves with an `InteractionId`. ### Method Signature `startInteraction(interactionName: string): Promise;` ### Parameters * **interactionName** (string) - The name of the interaction to track. ### Return Value * **InteractionId** (string) - A unique identifier for the interaction. ### Example ```javascript const interactionId = await NewRelic.startInteraction('StartLoadBadApiCall'); console.log(interactionId); ``` ``` -------------------------------- ### Initialize New Relic Agent with Basic Configuration Source: https://context7.com/newrelic/newrelic-react-native-agent/llms.txt Initialises the native New Relic agent and hooks into global error handlers. This function must be called once before any other API calls. Configure essential options like crash reporting, network requests, log level, and distributed tracing. ```javascript import NewRelic from 'newrelic-react-native-agent'; import { Platform } from 'react-native'; NewRelic.startAgent( Platform.OS === 'ios' ? 'IOS_APP_TOKEN' : 'ANDROID_APP_TOKEN', { crashReportingEnabled: true, networkRequestEnabled: true, logLevel: NewRelic.LogLevel.VERBOSE, offlineStorageEnabled: true, distributedTracingEnabled: true, } ); ``` -------------------------------- ### Configure Event Buffering and Storage Source: https://context7.com/newrelic/newrelic-react-native-agent/llms.txt Control how the agent buffers and stores events before uploading. Adjust harvest interval, in-memory event caps, and offline storage limits. ```javascript import NewRelic from 'newrelic-react-native-agent'; // More frequent uploads, smaller memory footprint, larger offline cache NewRelic.setMaxEventBufferTime(120); // harvest every 2 minutes NewRelic.setMaxEventPoolSize(500); // max 500 events in memory NewRelic.setMaxOfflineStorageSize(200); // 200 MB offline cache ``` -------------------------------- ### Get Current Session ID Source: https://context7.com/newrelic/newrelic-react-native-agent/llms.txt Returns the current session ID as a `Promise`. Useful for correlating New Relic session data with your own backend logging. ```javascript import NewRelic from 'newrelic-react-native-agent'; async function reportToBackend(eventData) { const sessionId = await NewRelic.currentSessionId(); await fetch('https://api.example.com/events', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ ...eventData, nrSessionId: sessionId }), }); } ``` -------------------------------- ### Apply New Relic Gradle Plugin (Plugins DSL) Source: https://github.com/newrelic/newrelic-react-native-agent/blob/main/README.md Configure your `android/settings.gradle` and `android/app/build.gradle` files to apply the New Relic Gradle plugin using the Plugins DSL. ```groovy 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.7.2" apply false // <-- include this } ``` ```groovy plugins { id "com.android.application" id "kotlin-android" id "com.newrelic.agent.android" //<-- include this } ``` -------------------------------- ### Demo Crash Reporting Source: https://context7.com/newrelic/newrelic-react-native-agent/llms.txt Throws a demo runtime exception to verify that crash reporting is working. For testing purposes only. ```APIDOC ## `crashNow(message?)` Throws a demo runtime exception to verify that crash reporting is working. The optional `message` string is attached to the exception. **For testing only — do not use in production.** ### Parameters - **message** (string) - Optional - A descriptive message to attach to the exception. ### Request Example ```javascript import NewRelic from 'newrelic-react-native-agent'; // No message NewRelic.crashNow(); // With a descriptive message NewRelic.crashNow('Test crash: verifying symbolication pipeline'); ``` ``` -------------------------------- ### Get Current Session ID - New Relic React Native Source: https://github.com/newrelic/newrelic-react-native-agent/blob/main/README.md Returns the current session ID as a Promise. Useful for consolidating monitoring data based on a single session identifier. ```javascript let sessionId = await NewRelic.currentSessionId(); ``` -------------------------------- ### Apply New Relic Gradle Plugin (Traditional) Source: https://github.com/newrelic/newrelic-react-native-agent/blob/main/README.md Configure your `buildscript` dependencies and apply the New Relic plugin in `android/app/build.gradle` using the traditional method. ```groovy buildscript { ... repositories { ... mavenCentral() } dependencies { ... classpath "com.newrelic.agent.android:agent-gradle-plugin:7.7.4" } } ``` ```groovy apply plugin: "com.android.application" apply plugin: 'newrelic' // <-- include this ``` -------------------------------- ### Initialize New Relic Agent in React Native Source: https://github.com/newrelic/newrelic-react-native-agent/blob/main/README.md Import and initialize the New Relic agent in your application's entry point. Ensure you replace placeholder tokens with your actual application tokens. The agent configuration allows customization of various monitoring features. ```javascript 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 = ''; } else { appToken = ''; } 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, }; NewRelic.startAgent(appToken,agentConfiguration); NewRelic.setJSAppVersion(appVersion.version); AppRegistry.registerComponent(appName, () => App); ``` -------------------------------- ### React Navigation Integration Source: https://github.com/newrelic/newrelic-react-native-agent/blob/main/README.md Integrate New Relic's routing instrumentation with React Navigation. This allows for automatic tracking of screen transitions. ```APIDOC ## React Navigation Integration ### Description Integrate New Relic's routing instrumentation with React Navigation to automatically track screen transitions. ### v5 Integration Set the `onStateChange` prop of `NavigationContainer` to `NewRelic.onStateChange`. ```javascript ``` ### <=v4 Integration Set the `onNavigationStateChange` prop of your App wrapper to `NewRelic.onNavigationStateChange`. ```javascript export default () => ( ); ``` ``` -------------------------------- ### logInfo Source: https://github.com/newrelic/newrelic-react-native-agent/blob/main/README.md Logs an informational message to the New Relic log. ```APIDOC ## logInfo(message: string): void; ### Description Logs an informational message to the New Relic log. ### Method `logInfo` ### Parameters #### Path Parameters - **message** (string) - Required - The informational message to log. ### Request Example ```javascript NewRelic.logInfo("User logged in"); ``` ``` -------------------------------- ### setMaxEventPoolSize Source: https://github.com/newrelic/newrelic-react-native-agent/blob/main/README.md Sets the maximum size of the event pool stored in memory until the next harvest cycle. The 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. ```APIDOC ## setMaxEventPoolSize(maxSize: number): void; ### Description Sets the maximum size of the event pool stored in memory until the next harvest cycle. ### Method `setMaxEventPoolSize` ### Parameters #### Path Parameters - **maxSize** (number) - Required - The maximum number of events to store in the event pool. ### Request Example ```javascript NewRelic.setMaxEventPoolSize(2000); ``` ``` -------------------------------- ### Event Buffering and Storage Configuration Source: https://context7.com/newrelic/newrelic-react-native-agent/llms.txt Controls how the agent buffers and stores events before uploading. These methods allow customization of harvest intervals, in-memory event limits, and offline storage size. ```APIDOC ## `setMaxEventBufferTime(seconds)` / `setMaxEventPoolSize(maxSize)` / `setMaxOfflineStorageSize(megaBytes)` Controls how the agent buffers and stores events before uploading. `setMaxEventBufferTime` sets the harvest interval (60–600 seconds, default 600). `setMaxEventPoolSize` caps in-memory events per cycle (default 1000). `setMaxOfflineStorageSize` limits persistent offline storage (default 100 MB). ### Example ```js import NewRelic from 'newrelic-react-native-agent'; // More frequent uploads, smaller memory footprint, larger offline cache NewRelic.setMaxEventBufferTime(120); // harvest every 2 minutes NewRelic.setMaxEventPoolSize(500); // max 500 events in memory NewRelic.setMaxOfflineStorageSize(200); // 200 MB offline cache ``` ``` -------------------------------- ### Upload Symbols for React Native Agent (1.3.1+) Source: https://github.com/newrelic/newrelic-react-native-agent/blob/main/README.md Use this script in Xcode build phases for symbol upload with React Native agent 1.3.1 or higher. Ensure the dsym-upload-tools are available. ```bash 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" ``` -------------------------------- ### Routing Instrumentation - React Navigation v4 and below Source: https://context7.com/newrelic/newrelic-react-native-agent/llms.txt Use `onNavigationStateChange` on the root `App` wrapper for older React Navigation APIs to instrument navigation events. ```javascript import React from 'react'; import { createAppContainer } from 'react-navigation'; import { createStackNavigator } from 'react-navigation-stack'; import NewRelic from 'newrelic-react-native-agent'; import HomeScreen from './screens/HomeScreen'; const AppNavigator = createStackNavigator({ Home: HomeScreen }); const AppContainer = createAppContainer(AppNavigator); export default () => ( ); ``` -------------------------------- ### Manually Record Breadcrumb for Screen Changes Source: https://github.com/newrelic/newrelic-react-native-agent/blob/main/README.md Manually report screen changes as breadcrumbs using `NewRelic.recordBreadcrumb` with screen name parameters. ```javascript var params = { 'screenName':'screenName' }; NewRelic.recordBreadcrumb('navigation',params); ``` -------------------------------- ### logAll Source: https://github.com/newrelic/newrelic-react-native-agent/blob/main/README.md Logs an exception with associated attributes to the New Relic log. This is useful for capturing detailed context around errors. ```APIDOC ## logAll(Error error, attributes?: {[key: string]: any}) : void ### Description Logs an exception with attributes to the New Relic log. ### Method logAll ### Parameters #### Path Parameters - **error** (Error) - Required - The error object to log. - **attributes** (object) - Optional - A key-value map of attributes to associate with the log entry. ### Request Example ```javascript Newrelic.logAll(new Error("This is an exception"), {"BreadNumValue": 12.3 , "BreadStrValue": "FlutterBread", "BreadBoolValue": true , "message": "This is a message with attributes" } ); ``` ``` -------------------------------- ### Trigger Demo Crash Source: https://context7.com/newrelic/newrelic-react-native-agent/llms.txt Throws a demo runtime exception to verify crash reporting is working. The optional `message` string is attached to the exception. For testing only. ```javascript import NewRelic from 'newrelic-react-native-agent'; // No message NewRelic.crashNow(); // With a descriptive message NewRelic.crashNow('Test crash: verifying symbolication pipeline'); ``` -------------------------------- ### Logging with Attributes Source: https://context7.com/newrelic/newrelic-react-native-agent/llms.txt Sends a log entry with a free-form attribute map to New Relic. `logAll` extracts the `.message` from an `Error` object and merges it with the supplied attributes. ```APIDOC ## `logAttributes(attributes)` / `logAll(error, attributes)` Sends a log entry with a free-form attribute map to New Relic. `logAll` extracts the `.message` from an `Error` object and merges it with the supplied attributes. ### Example ```js import NewRelic from 'newrelic-react-native-agent'; // Log a flat attribute map NewRelic.logAttributes({ message: 'Checkout flow completed', level: NewRelic.LogLevel.INFO, orderId: 'ORD-88231', totalAmount: 149.95, promoApplied: true, }); // Log an Error with contextual attributes try { await submitOrder(cart); } catch (e) { NewRelic.logAll(e, { level: NewRelic.LogLevel.ERROR, screen: 'Checkout', cartItemCount: cart.items.length, userId: currentUser.id, }); } ``` ``` -------------------------------- ### Set JavaScript Application Version Source: https://context7.com/newrelic/newrelic-react-native-agent/llms.txt Sets the JavaScript bundle version string, which is sent with every recorded JS error. Call this immediately after `startAgent`. This value is required for `recordError` to function correctly. ```javascript import NewRelic from 'newrelic-react-native-agent'; import * as pkg from './package.json'; NewRelic.startAgent(appToken, agentConfig); NewRelic.setJSAppVersion(pkg.version); // e.g. "2.4.1" // All subsequent recordError calls will include jsAppVersion: "2.4.1" ``` -------------------------------- ### Jest Configuration for New Relic Agent Source: https://github.com/newrelic/newrelic-react-native-agent/blob/main/README.md Configure Jest to correctly transform and mock the New Relic React Native agent. This involves updating `transformIgnorePatterns` and `setupFiles`. ```json "jest": { "preset": "react-native", "transformIgnorePatterns": [ "node_modules/(?!@react-native|react-native|newrelic-react-native-agent)" ], "setupFiles": [ "./node_modules/newrelic-react-native-agent/jestSetup.js" ] } ``` -------------------------------- ### iOS dSYM Upload Script Configuration Source: https://github.com/newrelic/newrelic-react-native-agent/blob/main/README.md Configuration for a New Run Script Build Phase in Xcode to automatically upload dSYM files for crash symbolication. Ensure the script is the last build script and replace APP_TOKEN with your actual token. ```bash # Add the following lines of code to the new phase and replace APP_TOKEN with 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. ``` -------------------------------- ### Upload Symbols for React Native Agent (0.0.7-) Source: https://github.com/newrelic/newrelic-react-native-agent/blob/main/README.md This script handles symbol upload for older React Native agent versions (0.0.7 or lower). It searches for the newrelic_postbuild.sh script in different locations. ```bash 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" ``` -------------------------------- ### Run Release Mode for iOS and Android Source: https://github.com/newrelic/newrelic-react-native-agent/blob/main/README.md Commands to run the React Native application in release mode, which will show fatal JS errors as crashes in New Relic. ```shell npx react-native run-ios --mode=release ``` ```shell npx react-native run-android --mode=release ``` -------------------------------- ### Simulate Crash - New Relic React Native Source: https://github.com/newrelic/newrelic-react-native-agent/blob/main/README.md Throws a demo run-time exception to test New Relic's crash reporting functionality. An optional message can be provided. ```javascript NewRelic.crashNow(); ``` ```javascript NewRelic.crashNow("New Relic example crash message"); ``` -------------------------------- ### setJSAppVersion Source: https://context7.com/newrelic/newrelic-react-native-agent/llms.txt Sets the JavaScript bundle version string, which is sent with every recorded JS error. This should be called immediately after `startAgent` and is required for `recordError` to function correctly. ```APIDOC ## setJSAppVersion(version) ### Description Sets the JavaScript bundle version string sent alongside every recorded JS error. Call this immediately after `startAgent`. The value is required for `recordError` to work correctly. ### Method `NewRelic.setJSAppVersion` ### Parameters - **version** (string) - Required - The version string of the JavaScript bundle (e.g., "2.4.1"). ### Request Example ```javascript import NewRelic from 'newrelic-react-native-agent'; import * as pkg from './package.json'; NewRelic.startAgent(appToken, agentConfig); NewRelic.setJSAppVersion(pkg.version); // e.g. "2.4.1" // All subsequent recordError calls will include jsAppVersion: "2.4.1" ``` ``` -------------------------------- ### crashNow Source: https://github.com/newrelic/newrelic-react-native-agent/blob/main/README.md Intentionally throws a runtime exception to test New Relic's crash reporting functionality. ```APIDOC ## crashNow ### Description Throws a demo run-time exception to test New Relic crash reporting. ### Method `crashNow(message?: string): void;` ### Parameters #### Path Parameters - **message** (string) - Optional - A message to include with the crash report. ### Request Example ```javascript NewRelic.crashNow(); NewRelic.crashNow("New Relic example crash message"); ``` ``` -------------------------------- ### Add HTTP Headers for Tracking Source: https://context7.com/newrelic/newrelic-react-native-agent/llms.txt Specifies an array of HTTP header names to be captured as attributes on `MobileRequest` and `MobileRequestError` events. Call this once during agent startup. ```javascript import NewRelic from 'newrelic-react-native-agent'; // Call once during agent startup NewRelic.addHTTPHeadersTrackingFor([ 'X-Request-Id', 'X-Correlation-Id', 'CF-Ray', 'X-Cache', ]); // Any subsequent network request containing these headers will have // their values recorded as event attributes in New Relic. ``` -------------------------------- ### Log Exception with Attributes Source: https://github.com/newrelic/newrelic-react-native-agent/blob/main/README.md Logs an exception along with custom attributes to the New Relic log. This provides more context for errors. ```javascript Newrelic.logAll(new Error("This is an exception"), {"BreadNumValue": 12.3 , "BreadStrValue": "FlutterBread", "BreadBoolValue": true , "message": "This is a message with attributes" } ); ``` -------------------------------- ### Xcode Build Settings for dSYM Generation Source: https://github.com/newrelic/newrelic-react-native-agent/blob/main/README.md Configure these build settings in Xcode to ensure dSYM files are generated correctly for symbol upload. This is crucial for debugging crash reports. ```text Debug Information Format : Dwarf with dSYM File Deployment Postprocessing: Yes Strip Linked Product: Yes Strip Debug Symbols During Copy : Yes ``` -------------------------------- ### Query JavaScript Errors (v1.2.0+) Source: https://github.com/newrelic/newrelic-react-native-agent/blob/main/README.md Use this NRQL query to view JavaScript errors and promise rejections in the 'Handled Exceptions' tab in New Relic One. ```sql SELECT * FROM MobileHandledException SINCE 24 hours ago ``` -------------------------------- ### Data Collection Feature Toggles Source: https://context7.com/newrelic/newrelic-react-native-agent/llms.txt Runtime toggles for specific data-collection features. These methods can be called after `startAgent` to change behavior dynamically. ```APIDOC ## `analyticsEventEnabled(enabled)` / `networkRequestEnabled(enabled)` / `networkErrorRequestEnabled(enabled)` / `httpResponseBodyCaptureEnabled(enabled)` Runtime toggles for specific data-collection features. Can be called after `startAgent` to change behaviour dynamically. `analyticsEventEnabled` is Android-only. ### Example ```js import NewRelic from 'newrelic-react-native-agent'; // Disable all network monitoring for a sensitive screen function onEnterPaymentScreen() { NewRelic.networkRequestEnabled(false); NewRelic.networkErrorRequestEnabled(false); NewRelic.httpResponseBodyCaptureEnabled(false); } // Re-enable after leaving the sensitive screen function onLeavePaymentScreen() { NewRelic.networkRequestEnabled(true); NewRelic.networkErrorRequestEnabled(true); NewRelic.httpResponseBodyCaptureEnabled(true); } // Android only NewRelic.analyticsEventEnabled(false); ``` ``` -------------------------------- ### Interaction Tracking Source: https://context7.com/newrelic/newrelic-react-native-agent/llms.txt Methods for wrapping code segments as New Relic Interaction traces. `startInteraction` initiates a trace, `endInteraction` concludes it, and `setInteractionName` renames the active trace (Android only). ```APIDOC ## `startInteraction(actionName)` / `endInteraction(interactionId)` / `setInteractionName(name)` Wraps a code segment as a named New Relic Interaction trace. `startInteraction` returns a `Promise` interaction ID that must be passed to `endInteraction`. `setInteractionName` renames the active interaction (Android only). ### Parameters #### `startInteraction` - **actionName** (string) - Required - The name of the interaction to start. #### `endInteraction` - **interactionId** (string) - Required - The ID of the interaction to end. #### `setInteractionName` - **name** (string) - Required - The new name for the active interaction. ### Request Example ```javascript import NewRelic from 'newrelic-react-native-agent'; async function loadProductCatalog() { const interactionId = await NewRelic.startInteraction('LoadProductCatalog'); try { const res = await fetch('https://api.example.com/products'); const data = await res.json(); return data; } catch (e) { NewRelic.recordError(e); return []; } finally { NewRelic.endInteraction(interactionId); } } // Android only: rename the running interaction async function doComplexWork() { const id = await NewRelic.startInteraction('InitialName'); NewRelic.setInteractionName('RenamedInteraction'); // ... work ... NewRelic.endInteraction(id); } ``` ``` -------------------------------- ### Log Attributes and Errors Source: https://context7.com/newrelic/newrelic-react-native-agent/llms.txt Sends a log entry with a free-form attribute map. `logAll` extracts the `.message` from an `Error` object and merges it with supplied attributes. ```javascript import NewRelic from 'newrelic-react-native-agent'; // Log a flat attribute map NewRelic.logAttributes({ message: 'Checkout flow completed', level: NewRelic.LogLevel.INFO, orderId: 'ORD-88231', totalAmount: 149.95, promoApplied: true, }); // Log an Error with contextual attributes try { await submitOrder(cart); } catch (e) { NewRelic.logAll(e, { level: NewRelic.LogLevel.ERROR, screen: 'Checkout', cartItemCount: cart.items.length, userId: currentUser.id, }); } ``` -------------------------------- ### Routing Instrumentation - React Native Navigation (Wix) Source: https://context7.com/newrelic/newrelic-react-native-agent/llms.txt Register `NewRelic.componentDidAppearListener` with the `Navigation.events()` API to record subsequent screen appearances as `MobileBreadcrumb` events. ```javascript import { Navigation } from 'react-native-navigation'; import NewRelic from 'newrelic-react-native-agent'; Navigation.events().registerComponentDidAppearListener( NewRelic.componentDidAppearListener ); // Subsequent screen appearances are recorded as MobileBreadcrumb events // with the component name as 'screenName'. ``` -------------------------------- ### React Native Navigation Integration Source: https://github.com/newrelic/newrelic-react-native-agent/blob/main/README.md Integrate New Relic's routing instrumentation with React Native Navigation by registering a listener for component appearance events. ```APIDOC ## React Native Navigation Integration ### Description Register `NewRelic.componentDidAppearListener` to instrument screen changes in React Native Navigation. ### Usage Use `Navigation.events().registerComponentDidAppearListener` to register the listener. ```javascript Navigation.events().registerComponentDidAppearListener(NewRelic.componentDidAppearListener); ``` ``` -------------------------------- ### Structured Logging Source: https://context7.com/newrelic/newrelic-react-native-agent/llms.txt Sends a structured log message to the New Relic log pipeline at the specified level. Supports generic logging with explicit levels and convenience wrappers for common levels. ```APIDOC ## `log(level, message)` / `logInfo` / `logError` / `logDebug` / `logVerbose` / `logWarn` Sends a structured log message to the New Relic log pipeline at the specified level. Log levels (least to most verbose): `ERROR`, `WARN`, `INFO`, `VERBOSE`, `AUDIT`, `DEBUG`. ### Example ```js import NewRelic from 'newrelic-react-native-agent'; // Generic log with explicit level NewRelic.log(NewRelic.LogLevel.WARN, 'Cart service responded slowly'); // Convenience wrappers NewRelic.logInfo('User completed onboarding flow'); NewRelic.logError('Payment gateway returned unexpected 503'); NewRelic.logDebug('Rendered ProductList with 48 items'); NewRelic.logVerbose('Cache hit for key: product_catalog_v2'); NewRelic.logWarn('Retry attempt 2/3 for order submission'); ``` ``` -------------------------------- ### recordCustomEvent Source: https://github.com/newrelic/newrelic-react-native-agent/blob/main/README.md Creates and records a custom event, which can be used for analysis in New Relic Insights. Allows for custom event types, names, and attributes. ```APIDOC ## recordCustomEvent ### Description Creates and records a custom event for use in New Relic Insights. ### Method `recordCustomEvent(eventType: string, eventName?: string, attributes?: {[key: string]: any}): void;` ### Parameters #### Path Parameters - **eventType** (string) - Required - The type of the custom event. - **eventName** (string) - Optional - The name of the custom event. - **attributes** (object) - Optional - A key-value map of attributes to associate with the custom event. ### Request Example ```javascript NewRelic.recordCustomEvent("mobileClothes", "pants", {"pantsColor": "blue","pantssize": 32,"belt": true}); ``` ``` -------------------------------- ### Expo Managed Workflow Configuration Source: https://github.com/newrelic/newrelic-react-native-agent/blob/main/README.md Configuration for integrating the New Relic agent into an Expo managed workflow using config plugins. Ensure `expo prebuild --clean` is run after updating `app.json`. ```json { "name": "my app", "plugins": ["newrelic-react-native-agent"] } ``` -------------------------------- ### Track HTTP Headers for Network Events Source: https://github.com/newrelic/newrelic-react-native-agent/blob/main/README.md Adds specified header field strings to a list that will be recorded as attributes with network request events in New Relic One. ```javascript NewRelic.addHTTPHeadersTrackingFor(["Car","Music"]); ``` -------------------------------- ### Event Recording: recordBreadcrumb Source: https://context7.com/newrelic/newrelic-react-native-agent/llms.txt Creates a `MobileBreadcrumb` event to mark application activities or screen transitions, useful for crash trail analysis. Attributes can be provided as a plain object or a `Map`. ```APIDOC ## `recordBreadcrumb(eventName, attributes?)` Creates a `MobileBreadcrumb` event to mark an app activity or screen transition useful for crash trail analysis. Attributes can be a plain object or a `Map`. ```js import NewRelic from 'newrelic-react-native-agent'; // Plain object NewRelic.recordBreadcrumb('UserAction', { action: 'checkout_started', cartTotal: 59.99, itemCount: 3, }); // Map const navParams = new Map([ ['screenName', 'ProductDetail'], ['productId', 'SKU-4821'], ]); NewRelic.recordBreadcrumb('navigation', navParams); // NRQL query to retrieve breadcrumbs: // SELECT * FROM MobileBreadcrumb WHERE appId = '' SINCE 1 hour ago ``` ``` -------------------------------- ### HTTP Header Tracking Configuration Source: https://context7.com/newrelic/newrelic-react-native-agent/llms.txt Specifies an array of HTTP header names whose values will be captured as attributes on `MobileRequest` and `MobileRequestError` events. ```APIDOC ## `addHTTPHeadersTrackingFor(headers)` Specifies an array of HTTP header names whose values will be captured as attributes on `MobileRequest` and `MobileRequestError` events. ### Parameters - **headers** (string[]) - Required - An array of HTTP header names to track. ### Request Example ```javascript import NewRelic from 'newrelic-react-native-agent'; // Call once during agent startup NewRelic.addHTTPHeadersTrackingFor([ 'X-Request-Id', 'X-Correlation-Id', 'CF-Ray', 'X-Cache', ]); // Any subsequent network request containing these headers will have // their values recorded as event attributes in New Relic. ``` ``` -------------------------------- ### Expo Managed Workflow Config Plugin Source: https://context7.com/newrelic/newrelic-react-native-agent/llms.txt For Expo managed workflow projects, the `app.json` file should include `"newrelic-react-native-agent"` in the `plugins` array to automatically configure the Android Gradle plugin and permissions. ```json // app.json { "expo": { "name": "MyApp", "plugins": ["newrelic-react-native-agent"] } } ``` ```bash # Install the package npx expo install newrelic-react-native-agent # Rebuild native code with the plugin applied npx expo prebuild --clean ``` -------------------------------- ### Log Warning Message in New Relic Source: https://github.com/newrelic/newrelic-react-native-agent/blob/main/README.md Use this method to log a warning message to the New Relic log. This helps in identifying potential issues. ```javascript NewRelic.logWarning("This is a warning message"); ``` -------------------------------- ### Log Message with Specified Level Source: https://github.com/newrelic/newrelic-react-native-agent/blob/main/README.md Logs a message to the New Relic log with a specified log level, such as INFO, WARN, ERROR, etc. Ensure LogLevel is imported or accessible. ```javascript NewRelic.log(LogLevel.INFO, "This is an informational message"); ``` -------------------------------- ### logWarning Source: https://github.com/newrelic/newrelic-react-native-agent/blob/main/README.md Logs a warning message to the New Relic log. Warnings indicate potential issues that do not necessarily stop the application but should be addressed. ```APIDOC ## logWarning(String message) : void ### Description Logs a warning message to the New Relic log. ### Method logWarning ### Parameters #### Path Parameters - **message** (String) - Required - The warning message to log. ### Request Example ```javascript NewRelic.logWarning("This is a warning message"); ``` ``` -------------------------------- ### Record Custom Events Source: https://context7.com/newrelic/newrelic-react-native-agent/llms.txt Use `recordCustomEvent` to create and store custom events in New Relic Insights. Specify a high-level `eventType` (aim for ~5 types) and a specific `eventName`. Attributes can be a plain object or a `Map`. ```javascript import NewRelic from 'newrelic-react-native-agent'; // Basic usage NewRelic.recordCustomEvent('UserAction', 'ProductPurchased', { productId: 'SKU-4821', price: 29.99, currency: 'USD', paymentMethod: 'credit_card', }); // With a Map const attrs = new Map([ ['screen', 'Checkout'], ['stepCompleted', 3], ['promoApplied', true], ]); NewRelic.recordCustomEvent('CheckoutFunnel', 'StepCompleted', attrs); // NRQL query: // SELECT * FROM UserAction WHERE name = 'ProductPurchased' SINCE 24 hours ago ``` -------------------------------- ### Set Maximum Offline Storage Size Source: https://github.com/newrelic/newrelic-react-native-agent/blob/main/README.md Configures the maximum total data size for offline storage. The default is 100MB. This storage is used for data payloads that fail to send due to no internet connection and is cleared once successfully sent. ```javascript NewRelic.setMaxOfflineStorageSize(200); ``` -------------------------------- ### Set Max Event Buffer Time Source: https://github.com/newrelic/newrelic-react-native-agent/blob/main/README.md Configures the duration of the event harvest cycle. The default is 10 minutes (600 seconds), with a minimum of 60 seconds and a maximum of 600 seconds. ```javascript NewRelic.setMaxEventBufferTime(60); ``` -------------------------------- ### logVerbose Source: https://github.com/newrelic/newrelic-react-native-agent/blob/main/README.md Logs a verbose message to the New Relic log. Verbose logging is typically used for detailed debugging information. ```APIDOC ## logVerbose(String message) : void ### Description Logs a verbose message to the New Relic log. ### Method logVerbose ### Parameters #### Path Parameters - **message** (String) - Required - The verbose message to log. ### Request Example ```javascript NewRelic.logVerbose("This is a verbose message"); ``` ``` -------------------------------- ### Event Recording: recordCustomEvent Source: https://context7.com/newrelic/newrelic-react-native-agent/llms.txt Creates and stores a custom event in New Relic Insights. `eventType` serves as a high-level category, while `eventName` provides a specific label within that type. Attributes can be a plain object or a `Map`. ```APIDOC ## `recordCustomEvent(eventType, eventName?, attributes?)` Creates and stores a custom event in New Relic Insights. `eventType` is a high-level category (keep to ~5 types); `eventName` is a specific label within that type. ```js import NewRelic from 'newrelic-react-native-agent'; // Basic usage NewRelic.recordCustomEvent('UserAction', 'ProductPurchased', { productId: 'SKU-4821', price: 29.99, currency: 'USD', paymentMethod: 'credit_card', }); // With a Map const attrs = new Map([ ['screen', 'Checkout'], ['stepCompleted', 3], ['promoApplied', true], ]); NewRelic.recordCustomEvent('CheckoutFunnel', 'StepCompleted', attrs); // NRQL query: // SELECT * FROM UserAction WHERE name = 'ProductPurchased' SINCE 24 hours ago ``` ```