How To Integrate Azure Application Insights Service To An Angular

Introduction

Today, we are going to see how to integrate Azure Application Insights into an Angular application. Application Insights is one of the Azure services. Application Insights is an analytic tool that monitors web application usage, performance, and exceptions. Please follow the below steps one by one.

  • Setup Application Insights to your Azure subscription
  • Configure Angular applications and dependencies
  • Installing the Application Insight Library
  • Integrate the Application Insights SDK in TypeScript
  • Error handling
  • View the Error exception in the Azure Portal

Setup application insights to your Azure subscription

If an Application Insights resource has not been added already or else you want to create a new one please visit portal.azure.com log in and create a resource.

Azure subscription

Application Insights

Review

AngularDemo

Configure Angular application and include dependencies

Get the instrumentation key value from application Insights into our Angular application. If your application was already built using the Angular CLI, then you will have an environment.ts file in your application.

Basically, the environment.ts file configures different settings at build time so we can also add the instrumentation key in the same file here. Please refer to the below codes.

export const environment = {
    appInsights: {
        instrumentationKey: 'xxxxxxxxxxxxxx'
    }
};

Installing Application Insights Libraries

The first thing we need to do is install the following NPM package.

npm install @microsoft/applicationinsights-web --save

application insights-web

JavaScript library supplied by Microsoft interfaces with the Application Insights SDK.

Integrate the application insights SDK in typeScript

Next, we want to create an “ApplicationInsightsService” that can handle logging exceptions, setting the logged-in user, and tracking page views. The service contents look like the below code.

import { Injectable } from '@angular/core';
import { ApplicationInsights, IExceptionTelemetry, DistributedTracingModes } from '@microsoft/applicationinsights-web';
import { Router, NavigationEnd } from '@angular/router';
import { filter } from 'rxjs/operators';
@Injectable({
  providedIn: 'root',
})
export class ApplicationInsightsService {
  private appInsights: ApplicationInsights;

  constructor(private router: Router) {
    this.appInsights = new ApplicationInsights({
      config: {
        instrumentationKey: "xxxxxxxxxxxxxx"
      }
    });
    this.appInsights.loadAppInsights();
    this.loadCustomTelemetryProperties();
    this.createRouterSubscription();
  }
  setUserId(userId: string) {
    this.appInsights.setAuthenticatedUserContext(userId);
  }
  clearUserId() {
    this.appInsights.clearAuthenticatedUserContext();
  }
  logPageView(name?: string, uri?: string) {
    this.appInsights.trackPageView({
      name,
      uri
    });
  }

  logException(error: Error) {
    let exception: IExceptionTelemetry = {
      exception: error
    };
    this.appInsights.trackException(exception);
  }
  private loadCustomTelemetryProperties() {
    this.appInsights.addTelemetryInitializer(envelope => {
      var item = envelope.baseData;
      item.properties = item.properties || {};
      item.properties["ApplicationPlatform"] = "Web";
      item.properties["ApplicationName"] = "ApplicationName";
    });
  }
  private createRouterSubscription() {
    this.router.events.pipe(filter(event => event instanceof NavigationEnd)).subscribe((event: NavigationEnd) => {
      this.logPageView(null, event.urlAfterRedirects);
    });
  }
}

After creating an instance of the class defined above ApplicationInsightsService, the application starts in the AppComponent. Declare ApplicationInsightsService like this.

export class AppComponent {
    constructor(private ApplicationInsightsService: ApplicationInsightsService) {}
}

Error Handling

The Application Insights JS packages should catch all unhandled errors. But in reality, Angular actually catches any internal errors, for example, a bug in your code, and has its own way of handling them.

We want to create an ErrorHandler implementation that does nothing but log the exception to AppInsights, and we want to print it out to the console and cross-check the code.

import { ErrorHandler, Injector, Injectable } from '@angular/core';
import { ApplicationInsightsService } from './application-insights.service';

@Injectable()
export class ApplicationInsightsErrorHandler implements ErrorHandler {
    constructor(private injector: Injector) {}

    handleError(error: any): void {
        this.injector.get<ApplicationInsightsService>(ApplicationInsightsService).logException(error);
        console.log(error);
    }
}

In our NGModule, we then want to create a provider for our error handler.

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';
import { AppComponent } from './app.component';

@NgModule({
    imports: [BrowserModule, FormsModule],
    declarations: [AppComponent],
    providers: [{
        provide: ErrorHandler,
        useClass: ApplicatioInsightsErrorHandler
    },],
    bootstrap: [AppComponent]
})
export class AppModule {}

Using Distributed tracing with CORS

If you are attempting to setup distributed tracing with CORS, while integrateApplicationInsightsc Service is pointing to an Azure domain and the front also points to another domain then we face the CORS issue. So we can resolve the issue in our ApplicationInsightsService file and add enableCorsCorrelationflag.

The first thing is that CORS is not turned on within the App Insights Angular library by default. To do so, in our ApplicationInsightsService we want to pass an extra flag when creating our ApplicationInsights object.

this.appInsights = new ApplicationInsights({
    config: {
        instrumentationKey: "xxxxxxxxxxxxxxxx",
        enableCorsCorrelation: true
    }
});

View the Error exception in the Azure portal

The included App Insights JS library will automatically send metrics to Application Insights. To view the exceptions, navigate to the Failure menu and choose the Exceptions tab. Make sure to toggle to Browser in the top right-hand corner.

Go to Azure Portal, and open AngularDemoApp Application Insights, The left side panel has the performance and failure menu available. Click the failure menu open the Exception menu and see the logs.

Azure Portal

Finally, we have received an exception log from the portal. I hope this article is most helpful for you. Thanks!


Similar Articles