Neurotic Programmer Masquerade

    newrelic-react-native-agent

    0.0.8 • Public • Published

    Community Plus header

    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.

    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 10
    • Depends on New Relic iOS/XCFramework and Android agents

    Native support levels are based on React Native requirements.

    Requirements

    Installation

    Yarn

    yarn add newrelic-react-native-agent

    NPM

    npm i newrelic-react-native-agent

    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 appVesrion 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,
    
        // 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: true,
    
        // 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.
        httpRequestBodyCaptureEnabled: true,
    
       //Android Specific
       // Optional: Enable or disable agent logging.
        loggingEnabled: true,
    
        //iOS Specific
        // Optional:Enable/Disable automatic instrumentation of WebViews
        webViewInstrumentation: true
      };
    
    
    NewRelic.startAgent(appToken,agentConfiguration);
    NewRelic.setJSAppVersion(appVesrion.version);
    AppRegistry.registerComponent(appName, () => App);

    AppToken is platform-specific. You need to generate the seprate token for Android and iOS apps.

    Android Setup

    1. Install the New Relic native Android agent (instructions here).
    2. Update build.gradle:
      buildscript {
        ...
        repositories {
          ...
          mavenCentral()
        }
        dependencies {
          ...
          classpath "com.newrelic.agent.android:agent-gradle-plugin:6.9.0"
        }
      }
    1. Update app/build.gradle:
      plugins {
        id 'newrelic'
      }
    
    1. Make sure your app requests INTERNET and ACCESS_NETWORK_STATE permissions by adding these lines to your AndroidManifest.xml
      <uses-permission android:name="android.permission.INTERNET" />
      <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    

    iOS Setup

    Run the following, and it will install the New Relic XCFramework agent:

      npx pod-install

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

    If you run following commands then Fatal JS erros will show up as a crash in NR.

    npx react-native run-ios --configuration Release
    
    npx react-native run-android --variant=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: After installing our package, add the config plugin to the plugins array of your app.json or app.config.js.
    {
      "name": "my app",
      "plugins": ["newrelic-react-native-agent"]
    }

    After this, you need to use the expo prebuild --clean command 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.

    Routing Instrumentation

    We currently provide two routing instrumentations out of the box to instrument route changes for and route changes record as Breadcrumb.

    • React Navigation

    • React Native Navigation

    • react-navigation

      • v5 set the onStateChange to NewRelic.onStateChange in your NavigationContainer as follows:

          <NavigationContainer
          onStateChange={  NewRelic.onStateChange  }  />
      • <=v4 set the onNavigationStateChange to NewRelic.onNavigationStateChange in your App wrapper as follows:

        export  default () => (
        <App
        onNavigationStateChange={ NewRelic.onNavigationStateChange  }  />
        );
    • react-native-navigation

      Register NewRelic.componentDidAppearListener listener 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]: boolean | number | string}): 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]: boolean | number | string}): 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();

    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. Supported failures are: Unknown, BadURL, TimedOut, CannotConnectToHost, DNSLookupFailed, BadServerResponse, SecureConnectionFailed

        NewRelic.noticeNetworkFailure('https://github.com', 'GET', Date.now(), Date.now(), '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. Supported measurements for countUnit and valueUnit are: PERCENT, BYTES, SECONDS, BYTES_PER_SECOND, OPERATIONS

        NewRelic.recordMetric('RNCustomMetricName', 'RNCustomMetricCategory');
        NewRelic.recordMetric('RNCustomMetricName', 'RNCustomMetricCategory', 12);
        NewRelic.recordMetric('RNCustomMetricName', 'RNCustomMetricCategory', 13, 'PERCENT', 'SECONDS');

    removeAllAttributes(): void;

    Removes all attributes from the session

        NewRelic.removeAllAttributes();

    recordError(e: string|error): void;

    Records javascript errors for react-native.

        try {
          var foo = {};
          foo.bar();
        } catch(e) {
          NewRelic.recordError(e);
        }

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

    httpRequestBodyCaptureEnabled(enabled: boolean) : void;

    Enable or disable capture of HTTP response bodies for HTTP error traces, and MobileRequestError events.

        NewRelic.httpRequestBodyCaptureEnabled(true);

    How to see JSErrors(Fatal/Non Fatal) in NewRelic One?

    There is no section for JavaScript errors, but you can see JavaScript errors in custom events and also query them in NRQL explorer.

    Screen Shot 2022-02-10 at 12 41 11 PM

    You can also build dashboard for errors using this query:

    SELECT jsAppVersion,name,Message,errorStack,isFatal FROM `JS Errors` SINCE 24 hours ago

    Symbolicating a stack trace

    Currently there is no symbolication of Javascript errors. Please follow the steps described here for Symbolication.

    Symbolication for Javascript errors are coming in future releases.

    * 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.
    

    Install

    npm i newrelic-react-native-agent

    DownloadsWeekly Downloads

    4,042

    Version

    0.0.8

    License

    New Relic

    Unpacked Size

    241 kB

    Total Files

    64

    Last publish

    Collaborators

    • newrelic