React Application Insights Module
Switch branches/tags
Nothing to show
Clone or download
Latest commit a604d7b Aug 23, 2018

README.md

react-appinsights

React Application Insights Module

JavaScript module to include Application Insights to application built with React. It extends standard Application Insights functionality with additional react specific features:

  • Tracking router changes.
  • React components usage statistics.
  • API to extend standard telemetry with additional dimensions.

Installation

With npm:

npm install react-appinsights --save

Usage

Initialize AppInsights

To initialize Application Insights add following to index.js:

    var ReactAI  = require('react-appinsights');
    ReactAI.init({instrumentationKey:'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxxx'});

See How to get instrumentation key for Applicaton Insights for more details.

Track router changes

a. Using react-router history object:

    import ReactAI from 'react-appinsights';
    import {Router, browserHistory} from 'react-router';

    ReactAI.init({instrumentationKey:'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxxx'}, browserHistory);

Or

b. Using Router.onUpdate:

    var ReactAI  = require('react-appinsights');
    ReactAI.init({instrumentationKey:'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxxx'});

    <Router routes={routes} history={browserHistory} onUpdate={ReactAI.trackRouterChange}/>

Enable React component usage tracking

To enable React component usage tracking, inherit from TrackedComponent

    var TrackedComponent = require ('react-appinsights').TrackedComponent;

    class MyComponent extends TrackedComponent{
        ...
    }

TrackedComponent uses ComponentWillUnmount and ComponentWillMount events to send telemetry, so if you override those, don't forget to call base methods:

    componentWillMount() {
        super.componentWillMount();
        ..
    }

We will measure time from ComponentWillMount event through ComponentWillUnmount event. However, in order to make this time more accurate it will subtract idle time.

This means that Router Component Engaged Time = ComponentWillUnmount timestamp - ComponentWillMount timestamp - idle time.

To see this metric in Azure portal you need to navigate to Application Insights resource, select Metrics Explorer from the top menu and configure one of the empty charts to display Custom metrics "React Component Engaged Time" grouped by Component Name. It can take up to 10 minutes for new custom metric to appear in Azure Portal.

Set Application Context

To augment all telemetry with aditional properties use ReactAI.setAppContext method:

E.g.

    ReactAI.setAppContext({urlReferrer:document.referrer});

This will add urlReferrer property to all page views, ajax calls, exceptions and other telemetry sent to Application Insights:

Get AppInsights object

Use following method to get original AppInsight object:

    var AppInsigts = ReactAI.ai();

Refer to this doc for information on Application Insights SDK JavaScript API.