@sigao/ng-application-insights

This library provides an Angular service to interact with Microsoft's Application Insights.

Usage no npm install needed!

<script type="module">
  import sigaoNgApplicationInsights from 'https://cdn.skypack.dev/@sigao/ng-application-insights';
</script>

README

NgApplicationInsights

This library provides an Angular service to interact with Microsoft's Application Insights.

Usage

Install the package

Run npm install @sigao/ng-application-insights

Create configuration object

This object will be used by the library to configure peripheral functionality and Application Insights

const ngAppInsightsConfig = {

    // [Optional] Enables logging to Application Insights
    enabled: true,

    // [Optional] Track page changes using angular router
    trackRoutedPages: true, 

    // [Required] Configuration for application insights 
    appInsightsConfig: {
      instrumentationKey: 'your_key_here',
      // property 2....
      // property 3....
    },

    // [Optional] Properties to be appended to every logging event's properties
    globalProperties: {
      appVersion: '1.0.0'
    }

    // [Optional] Enables automatic intercepting of errors. NOTE: This will override the default interceptor behavior included in @microsoft/applicationinsights-web
    interceptErrors: true
};

Configuration property: enabled

This flag enables/disables the service. Logging events made with this flag set to false will do nothing. Typically, this flag would be set to "false" for development environments and changed to "true" in production.

Configuration property: trackRoutedPages

This flag enables/disables automatic page tracking via Angular's router. If enabled, navigation events will automatically trigger application insight's "startTrackPage" and "stopTrackPage" events during navigation. If you require extra metrics or paremters for your page tracking events, disabled this property and manually use startTrackPage/stopTrackPage via the NgApplicationInsights service.

Configuration property: appInsightsConfig

This object represents Microsoft's configuration for Application Insights. A detailed description of this object can be found here. If your App Insights configuration relies on an external configuration source, you may need to wait until the application loads before initializing the service. If that is the case, do not include the this property and instead use the "init" function in the NgApplicationInsightsService.

Configuration property: globalProperties

This object will be merged with any properties included in a logging event. Global properties will be included even if no logging properties are provided to a logging event.

Configuration property: interceptErrors

This property determines if the system will use a global error intercepter. This intercepter will catch any unhandled errors in the system and report them to app insights. The default setting is "true".

NOTE: local properties supplied to individual logging events will override global properties if the same property name is used.

Import the module

Place the following code in your app imports. Providing the configuration object here is optional.

import { NgApplicationInsightsModule } from '@sigao/ng-application-insights';

@NgModule({
  declarations: [
    AppComponent,
  ],
  imports: [
    // ...,
    // ...,
    NgApplicationInsightsModule.forRoot(ngAppInsightsConfig) // Send config here if you know your settings at app start
  ],
  bootstrap: [AppComponent]
})

Using the service

Once the module is included, all you need to do is inject the service. Once injected you will be able to use logging functions as defined here.

import { NgApplicationInsightsService } from '@sigao/ng-application-insights';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent {
  constructor(public aiService: NgApplicationInsightsService) {
  
      // Example
      this.aiService.trackPageView({
          name: 'app_root_page'
        });
  }
}

Initializing Application Insights AFTER app load

As mentioned above, certain circumstances (such as usage of a CICD process) may force you to wait until after app load to initialize the service. If this is the case, do not send the configuration object to the module's "forRoot" function. Instead, provide the configuration object to the service's "init" function:

import { NgApplicationInsightsService } from '@sigao/ng-application-insights';
import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent {

  constructor(public aiService: NgApplicationInsightsService) {
   
  this.aiService.init(ngAppInsightsConfig).then(aiContext => {
      console.log('AI LOADED!');
      this.aiService.trackPageView({
          name: 'app_root_page',
          uri: '/'
        });
    });
  }
}

Accessing Application Insights object directly

If needed, the Application Insights object can be accessed directly via this.aiService.ai

Testing

If you want to write unit tests for services/components that rely on an external library such as this one, you will need to provide your tests with a mock representation of the service so as to not log actual analytics events during testing. We go you covered!

Just import the NgApplicationInsightsTestingModule into your TestBed module like so:

import { NgApplicationInsightsTestingModule } from '@sigao/ng-application-insights';

describe('AppComponent', () => {
  beforeEach(async(() => {
    TestBed.configureTestingModule({
      imports: [
        NgApplicationInsightsTestingModule
      ],
      declarations: [
        AppComponent
      ],
    }).compileComponents();
  }));

  it('should create the app', () => {
    const fixture = TestBed.createComponent(AppComponent);
    const app = fixture.debugElement.componentInstance;
    expect(app).toBeTruthy();
  });
});

This will automatically provide a mock instance of NgApplicationInsights to your tests without logging actual events.

Change Log

13.0.2 - Angular 13

1.4.0 Angular 10

  • Upgraded peer dependencies to target Angular 10
  • Tested functionality against Angular 10

1.3.1 - 1.3.2 New Org!

  • Migrated package to our company org

1.3 Error interceptor

  • Added automatic error intercepting (can be controlled via configuration object)
  • Fixed minor issue with error logging function parameters

1.2.5

  • Changed module definition to provide service without requiring usage "forRoot" (For configuring the service after app load)

1.2.4

  • Fixed AOT compilation issues

1.2.1 to 1.2.3 Turns out I'm dumb

  • Fixed packaging settings to have proper exports
  • Learned how npm publishing works...
  • Fixed promise chaining to allow AI context in "init" promise

1.2.0 (Now with 30% more testing FREE)

  • Added ability to import NgApplicationInsightsTestingModule for easier unit testing
  • Increased unit test coverage for all services
  • Updated global property merge to prioritize local properties supplied to events (eg. If global properties are set to { appVersion: '1.0.0' } and an event is dispatched with properties { appVersion: '1.0.1' } the final properties sent to app insights will be { appVersion: '1.0.1' }).

Powered By Sigao

This package is designed to be used within our tech stack to support our development efforts. While significant effort has been made to ensure that these packages are tested and maintained, mistakes happen, and there is a good possibility the bug won't be addressed unless it directly impacts our specific use case.

If you encounter a bug that you'd like addressed, feel free to reach out to us and we'll see what we can do!