Giter Club home page Giter Club logo

applicationinsights-react-native's Introduction

Microsoft Application Insights JavaScript SDK - React Native Plugin

React Native Plugin for the Application Insights Javascript SDK

Getting Started

By Default: This plugin relies on react-native-device-info. You must install and link this package. Keep react-native-device-info up-to-date to collect the latest device names using your app.

Since v3, support for accessing the DeviceInfo has been abstracted into an interface IDeviceInfoModule to enable you to use / set your own device info module. This interface uses the same function names and result react-native-device-info.

Note for Expo Users: If you are using Expo, which does not support the react-native-device-info package, you have an alternative option. You can use the React Native Manual Device Plugin instead. Please refer to the README-manual for further details on how to integrate it.

npm install --save @microsoft/applicationinsights-react-native @microsoft/applicationinsights-web
npm install --save react-native-device-info
react-native link react-native-device-info

Initializing the Plugin

To use this plugin, you only need to construct the plugin and add it as an extension to your existing Application Insights instance.

import { ApplicationInsights } from '@microsoft/applicationinsights-web';
import { ReactNativePlugin } from '@microsoft/applicationinsights-react-native';

var RNPlugin = new ReactNativePlugin();
var appInsights = new ApplicationInsights({
    config: {
        instrumentationKey: 'YOUR_INSTRUMENTATION_KEY_GOES_HERE',
        extensions: [RNPlugin]
    }
});
appInsights.loadAppInsights();

Disabling automatic device info collection

import { ApplicationInsights } from '@microsoft/applicationinsights-web';

var RNPlugin = new ReactNativePlugin();
var appInsights = new ApplicationInsights({
    config: {
        instrumentationKey: 'YOUR_INSTRUMENTATION_KEY_GOES_HERE',
        disableDeviceCollection: true,
        extensions: [RNPlugin]
    }
});
appInsights.loadAppInsights();

Using your own device info collection class

import { ApplicationInsights } from '@microsoft/applicationinsights-web';

// Simple inline constant implementation
const myDeviceInfoModule = {
    getModel: () => "deviceModel",
    getDeviceType: () => "deviceType",
    // v5 returns a string while latest returns a promise
    getUniqueId: () => "deviceId",         // This "may" also return a Promise<string>
};

var RNPlugin = new ReactNativePlugin();
RNPlugin.setDeviceInfoModule(myDeviceInfoModule);

var appInsights = new ApplicationInsights({
    config: {
        instrumentationKey: 'YOUR_INSTRUMENTATION_KEY_GOES_HERE',
        extensions: [RNPlugin]
    }
});

appInsights.loadAppInsights();

Requirements

You must be using a version >=2.0.0 of @microsoft/applicationinsights-web. This plugin will only work in react-native apps, e.g. it will not work with expo.

Device Information Collected

By default, this plugin automatically collects

  • Unique Device ID (also known as Installation ID)
  • Device Model Name (iPhone XS, etc.)
  • Device Type (Handset, Tablet, etc.)

IDeviceInfoModule

/**
 * Interface to abstract how the plugin can access the Device Info, this is a stripped
 * down version of the "react-native-device-info" interface and is mostly supplied for
 * testing.
 */
export interface IDeviceInfoModule {
    /**
     * Returns the Device Model
     */
    getModel: () => string;

    /**
     * Returns the device type
     */
    getDeviceType: () => string;

    /**
     * Returns the unique Id for the device, to support both the current version and previous
     * versions react-native-device-info, this may return either a `string` or `Promise<string>`,
     * when a promise is returned the plugin will "wait" for the promise to `resolve` or `reject`
     * before processing any events. This WILL cause telemetry to be BLOCKED until either of these
     * states, so when returning a Promise it MUST `resolve` or `reject` it can't just never resolve.
     * There is a default timeout configured via `uniqueIdPromiseTimeout` to automatically unblock
     * event processing when this issue occurs.
     */
    getUniqueId: () => Promise<string> | string;
}

If events are getting "blocked" because the Promise returned via getUniqueId is never resolved / rejected you can call setDeviceId() on the plugin to "unblock" this waiting state. There is also an automatic timeout configured via uniqueIdPromiseTimeout (defaults to 5 seconds), which will internally call setDeviceId() with any previously configured value.

Compatibility Matrix

Version Application Insights React Native Branch
4.1.0 ^3.1.0 *
dev:^0.69.9
main
4.0.3 ^3.0.8 *
dev:^0.69.9
main
4.0.2 ^3.0.5 *
dev:^0.69.9
main
4.0.1 ^3.0.3 *
dev:^0.69.9
main
4.0.0 ^3.0.2 *
dev:^0.69.9
main
3.0.3 ^2.8.14 *
dev:^0.69.9
release3.x
3.0.2 ^2.8.12 *
dev:^0.69.9
main
3.0.1 ^2.8.10 *
dev:^0.69.8
main
3.0.0 ^2.8.5 *
dev:^0.69.3
main
2.5.6 ^2.8.5 *
dev:^0.68.0
main <-- First release from this repo
2.5.5 2.8.5 *
dev:^0.68.0
main and [AI master](https://github.com/microsoft/ApplicationInsights-JS/tree/master/extensions/
2.5.4 2.8.4 *
dev:^0.68.0
[AI master](https://github.com/microsoft/ApplicationInsights-JS/tree/master/extensions/
2.5.3 2.8.3 *
dev:^0.68.0
[AI master](https://github.com/microsoft/ApplicationInsights-JS/tree/master/extensions/
2.5.2 2.8.2 *
dev:^0.68.0
[AI master](https://github.com/microsoft/ApplicationInsights-JS/tree/master/extensions/
2.5.1 2.8.1 *
dev:^0.68.0
[AI master](https://github.com/microsoft/ApplicationInsights-JS/tree/master/extensions/
2.5.0 2.8.0 *
dev:^0.68.0
[AI master](https://github.com/microsoft/ApplicationInsights-JS/tree/master/extensions/
2.4.4 2.7.4 *
dev:^0.64.2
[AI master](https://github.com/microsoft/ApplicationInsights-JS/tree/master/extensions/
2.4.3 2.7.3 *
dev:^0.64.2
[AI master](https://github.com/microsoft/ApplicationInsights-JS/tree/master/extensions/
2.4.2 2.7.2 *
dev:^0.64.2
[AI master](https://github.com/microsoft/ApplicationInsights-JS/tree/master/extensions/
2.4.1 2.7.1 *
dev:^0.64.2
[AI master](https://github.com/microsoft/ApplicationInsights-JS/tree/master/extensions/
2.4.0 2.7.0 *
dev:^0.64.2
[AI master](https://github.com/microsoft/ApplicationInsights-JS/tree/master/extensions/
2.3.5 ^2.6.5 *
dev:0.64.2
[AI master](https://github.com/microsoft/ApplicationInsights-JS/tree/master/extensions/
2.3.4 ^2.6.4 *
dev:0.64.2
[AI master](https://github.com/microsoft/ApplicationInsights-JS/tree/master/extensions/
2.3.3 ^2.6.3 *
dev:0.64.2
[AI master](https://github.com/microsoft/ApplicationInsights-JS/tree/master/extensions/
2.3.2 ^2.6.2 *
dev:0.63.2
[AI master](https://github.com/microsoft/ApplicationInsights-JS/tree/master/extensions/
2.3.1 ^2.6.2 *
dev:0.59.8
[AI master](https://github.com/microsoft/ApplicationInsights-JS/tree/master/extensions/
2.3.0 ^2.6.0 *
dev:0.59.8
[AI master](https://github.com/microsoft/ApplicationInsights-JS/tree/master/extensions/

Nightly Builds

To aid with testing and validation we also produce and publish nightly builds whenever there is a change from the previous build. These builds are published to the NpmJs registry on a successful build / test pass.

This process also tags the source code so that we can track the specific changes included using a nightly build specific version number which is the format "nightly-yymm-##" eg. nightly-2208-02

These nightly builds will not be retained indefinitely and should only be used for pre-production testing and/or validation of any changes that have not yet been released.

NPM

The NPM builds are tagged as "nightly" and can by downloaded using this as the version number npm install @microsoft/applicationinsights-react-native@nightly or using the nightly specific version number which is "nightly.yyyymm-###" (npm install @microsoft/[email protected]) where ## is the specific build number for the month (Note, slightly different version from the source code tag due to compatibility issues between the different systems).

Deployment process

When a new release is deployed the following occurs as part of the release

  • NPM packages are created and published to NpmJs

Contributing

This project welcomes contributions and suggestions. Most contributions require you to agree to a Contributor License Agreement (CLA) declaring that you have the right to, and actually do, grant us the rights to use your contribution. For details, visit https://cla.microsoft.com.

When you submit a pull request, a CLA-bot will automatically determine whether you need to provide a CLA and decorate the PR appropriately (e.g., label, comment). Simply follow the instructions provided by the bot. You will only need to do this once across all repositories using our CLA.

This project has adopted the Microsoft Open Source Code of Conduct. For more information see the Code of Conduct FAQ or contact [email protected] with any additional questions or comments.

Data Collection

As this SDK is designed to enable applications to perform data collection which is sent to the Microsoft collection endpoints the following is required to identify our privacy statement.

The software may collect information about you and your use of the software and send it to Microsoft. Microsoft may use this information to provide services and improve our products and services. You may turn off the telemetry as described in the repository. There are also some features in the software that may enable you and Microsoft to collect data from users of your applications. If you use these features, you must comply with applicable law, including providing appropriate notices to users of your applications together with a copy of Microsoft's privacy statement. Our privacy statement is located at https://go.microsoft.com/fwlink/?LinkID=824704. You can learn more about data collection and use in the help documentation and our privacy statement. Your use of the software operates as your consent to these practices.

Trademarks

This project may contain trademarks or logos for projects, products, or services. Authorized use of Microsoft trademarks or logos is subject to and must follow Microsoft's Trademark & Brand Guidelines. Use of Microsoft trademarks or logos in modified versions of this project must not cause confusion or imply Microsoft sponsorship. Any use of third-party trademarks or logos are subject to those third-party's policies.

License

MIT

applicationinsights-react-native's People

Contributors

aaronpowell avatar abaranch avatar capfei avatar hectorhdzg avatar karlie-777 avatar l2aelba avatar maxshehovtsov avatar microsoft-github-operations[bot] avatar microsoft-github-policy-service[bot] avatar microsoftopensource avatar msnev avatar ramthi avatar siyuniu-ms avatar steven-johnson-1977 avatar xiao-lix avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar

applicationinsights-react-native's Issues

Update to React-Native 0.69.x

Update to the latest version of React Native to address dependent component security issues and keep this plugin up to date.

React Native Expo Support

Is your feature request related to a problem? Please describe.

Looking through the code for the react-native plugin, I didn't find much that would preclude support for Expo. The main issue I saw is the peer dependency on react-native-device-info, but if the plugin allowed the consumer to inject something which meets that same interface at run time(e.g. something like IDeviceInfo), I couldn't see a reason that expo would not work. Expo exposes all the data needed to satisfy that interface using libraries which are Expo-compatible.

Is there something I have missed?

I'd be excited to open a PR or create a separate extension and share code between the two if a separate extension or alternative approach was preferred to avoid a breaking change.

Describe the solution you'd like

Consumers of this library for RN can inject their own service to provide the device info at initialization, removing need for peer dependency on react-native-device-info. This would be a breaking change for current consumers.

Describe alternatives you've considered

I'd like to use this package for expo and it is explicitly noted that expo will not work. The other option would be to create a separate plugin, however, the two would be nearly identical with the exception of how device info is initialized.

Additional context

Exceptions not automatically collected on React Native (0.60.4)

I've installed app insights web and the react native plugins, but I can't seem to get the automatic logging of exceptions to work when I throw an Error in my code; is there additional configuration needed?

@microsoft/applicationinsights-react-native: 1.0.3
@microsoft/applicationinsights-web: 2.2.2
react-native-device-info: 2.3.2

React native version 0.60.4

Set up is standard, as per documentation:

const RNPlugin = new ReactNativePlugin();
const appInsights = new ApplicationInsights({
    config: {
        instrumentationKey: 'my key',
        extensions: [RNPlugin],
    },
});
appInsights.loadAppInsights();

I've noticed when I set enableDebugExceptions: true then manually trigger a call to appInsights.trackException({exception: new Error('some error')});, I get an error which I can only assume is stopping this being logged?

AI (Internal): 35 message:"trackException failed, exception will not be collected: " props:"{exception:[object Object]{\messageId\:0,\message\:\AI (Internal): 0 message:\\\Browser does not support local storage. Session durations will be inaccurate.\\\\}}"

Thanks!

[BUG] Expo Support - disableDeviceCollection

Description/Screenshot
"Disabling automatic device info collection" documentation says disableDeviceCollection needs to be initialized on ApplicationInsights config. However, ApplicationInsights config does not recognize this property.

If disableDeviceCollection is initialized on ReactNativeManualDevicePlugin the Android bundling tasks still fails on exception "Unable to resolve 'react-native-device-info'"

If then installing react-native-device-info' you'll end up to exception "NativeModule.RNDeviceInfo is null".

Steps to Reproduce

  • React-Native Version: 0.72.3
  • SDK Version [e.g. 22]:
    "@microsoft/applicationinsights-react-native": "^4.0.0",
    "@microsoft/applicationinsights-web": "^3.0.2",
  • How you initialized the SDK:
    const RNMPlugin = new ReactNativeManualDevicePlugin({ disableDeviceCollection: true, }) const appInsights = new ApplicationInsights({ config: { instrumentationKey: 'YOUR_INSTRUMENTATION_KEY_GOES_HERE', extensions: [RNMPlugin], }, }) appInsights.loadAppInsights()

Expected behavior
Device info collection would be ignored

Additional context
This might be just documentation issue which needs to be clarified more.

[BUG] React Native: Not setting correlation headers on fetch requests

Description/Screenshot
Hi

We're trying to integrate our React Native app with Applications Insight but we're facing multiple issues. Mainly, it's not setting correlation headers (Request-Id, Request-Context etc.).

Steps to Reproduce

OS/Browser:

  • "react-native": "0.63.3",

SDK Version [e.g. 22]:

  • "@microsoft/applicationinsights-react-native": "^2.3.5",
  • "@microsoft/applicationinsights-web": "^2.6.5",

How you initialized the SDK:

import { ApplicationInsights } from '@microsoft/applicationinsights-web';
import { ReactNativePlugin } from '@microsoft/applicationinsights-react-native';
import { applicationInsightsKey } from 'react-native-dotenv';

let appInsights;

export function setupApplicationInsights() {
  var RNPlugin = new ReactNativePlugin();
  appInsights = new ApplicationInsights({
    config: {
      instrumentationKey: applicationInsightsKey,
      disableAjaxTracking: false,
      extensions: [RNPlugin],
      samplingPercentage: 100,
      loggingLevelTelemetry: 2,
      diagnosticLogInterval: 100,
      disableFetchTracking: false,
      disableCorrelationHeaders: false,
      enableCorsCorrelation: true,
      enableRequestHeaderTracking: true,
      enableResponseHeaderTracking: true,
    },
  });

  appInsights.loadAppInsights();

  var telemetryInitializer = envelope => {
    if (envelope.baseData.name != null && envelope.baseData.name.includes('heartbeat')) {
      return false;
    }

    envelope.tags['ai.cloud.role'] = 'courier-app';
    envelope.tags['ai.cloud.roleInstance'] = 'courier-app';
  };

  appInsights.addTelemetryInitializer(telemetryInitializer);
}

Expected behavior

We thought this would add the necessary headers to each fetch request and also send the necessary tracking data to the AI backend but it seems we're only getting some data in to AI which is not being correlated with our other services.

Additional context
We managed to get the application to send correlation data by adding this hack before we initialize AI.

  global.fetch.polyfill = false;

But this feels like a bad thing to do and it still didn't correlate the requests in the application map.

We're using react-navigation v5 and are sending appInsights.trackPageView(/*data*/) on each screen change. These page views does show in AI.

So our biggest issues right now are:

  1. Data isn't being correlated correctly in the Application Map view.
  2. Transactions aren't being grouped in a sane way in the end-to-end transactions view. They all seem to fall under the same operation id which we're not sure how to fix.

[BUG] `Type 'ReactNativePlugin' is not assignable to type 'ITelemetryPlugin'.`

Description
Same as this issue microsoft/applicationinsights-react-js#32

Tried with the following versions:

  • @microsoft/applicationinsights-react-native v3.0.3
  • @microsoft/applicationinsights-web v3.0.2

and

  • @microsoft/applicationinsights-react-native v4.0.0-nightly.2306-02
  • @microsoft/applicationinsights-web v3.0.3-nightly3.2306-01

Steps to Reproduce

import { ApplicationInsights } from '@microsoft/applicationinsights-web';
import { ReactNativePlugin } from '@microsoft/applicationinsights-react-native';

var RNPlugin = new ReactNativePlugin();
var appInsights = new ApplicationInsights({
    config: {
        instrumentationKey: 'YOUR_INSTRUMENTATION_KEY_GOES_HERE',
        extensions: [RNPlugin]
    }
});
appInsights.loadAppInsights();

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.