Laurie Atkinson, Senior Premier Developer Consultant, outlines the steps and pieces you need to add logging and telemetry to an Angular SPA using Application Insights.
*There was an updated follow-up to this article on 3/29/20– Be sure and see Angular How-to: Add Application Insights to an Angular SPA.
Application Insights is an Azure service for monitoring web applications. It includes analytics tools to help you understand application usage and to diagnose issues with the goal of continuously improving performance and usability. In addition to its integration with a variety of backend web platforms, Application Insights also includes browser analytics.
The following steps are specifically targeted at the front-end developers building with Angular and TypeScript that want to start tracking their Single Page Applications.
Step 1 – Add Application Insights to your Azure subscription
- Navigate to portal.azure.com and log in.
- If an Application Insights resource has not been added yet (or you want to create a new one), select Add Monitoring + Management Application Insights
- Fill in the required fields and click Create.
- After the resource has been added, navigate to it via a search for Application Insights and note the instrumentation key located in the properties blade. This key is required to communicate between your web application and Application Insights.
Step 2 – Configure Angular application and include dependencies
- Copy the instrumentation key into the Angular application. If your app was build using the Angular CLI, then you will have an environment.ts file which is a good place to store the instrumentation key. You may choose another file or service, but this key must be included in your project somewhere.
export const environment = {
. . .
appInsights: {
instrumentationKey: 'b0137cf3-7ae6-4309-8925-06a3b1c20508'
}
};
- Add two dependencies to package.json and restore them using npm install.
"dependencies": {
"applicationinsights-js": "^1.0.8"
},
"devDependencies": {
"@types/applicationinsights-js": "^1.0.2",
}
applicationinsights-js – JavaScript library supplied by Microsoft to interface with the Application Insights SDK. Documentation on this library is located here:
@types/applicationinsights-js – TypeScript type definition file for applicationinsights-js.
Step 3 – Consume the Application Insights SDK in TypeScript
- Create a TypeScript class as a wrapper around the Application Insights JavaScript API and import the AppInsights class using the module loading system. Include methods for each method in the SDK that you want to support.
import { Injectable } from '@angular/core';
import { environment } from '../../../environments/environment';
import { AppInsights } from 'applicationinsights-js';
@Injectable()
export class MyMonitoringService {
private config: Microsoft.ApplicationInsights.IConfig = {
instrumentationKey: environment.appInsights.instrumentationKey
};
constructor() {
if (!AppInsights.config) {
AppInsights.downloadAndSetup(this.config);
}
}
logPageView(name?: string, url?: string, properties?: any,
measurements?: any, duration?: number) {
AppInsights.trackPageView(name, url, properties, measurements, duration);
}
logEvent(name: string, properties?: any, measurements?: any) {
AppInsights.trackEvent(name, properties, measurements);
}
. . .
}
On creation, the service calls into the Application Insights SDK JavaScript API, which triggers the download of ai.js from a CDN. This is recommended to ensure that the latest JavaScript is running against the Application Insights API.
If you are using the Angular CLI and webpack, then applicationinsights-js will be automatically included in the vendor bundle. If you are using SystemJS instead, you will need to make sure this module is included. It is located under node_modules in this path:
- Create an instance of the class created in step 7 as soon as the application starts in the AppComponent.
import { Component } from '@angular/core';
import { MyMonitoringService } from './framework/logging/monitoring.service';
@Component({
. . .
})
export class AppComponent {
constructor(private myMonitoringService: MyMonitoringService) {
}
}
- The included JavaScript library will automatically send a number of metrics to Application Insights which are viewable in the Azure Portal under the Browser blade. Highlighted here are Page Views, Exceptions, and AJAX calls.
- Due to the nature of a Single Page Application (SPA), page transitions do not occur that would automatically trigger logging to Application Insights. To track the user’s activity as s/he navigates from page to page, a call must be made manually to trackPageView(). Rather than require the programmer to include this code in every component, you can include a base component and any component that should be tracked should inherit from this base class.
import { Component, ReflectiveInjector } from '@angular/core';
import { MyMonitoringService } from '../logging/monitoring.service';
@Component({
template: ''
})
export class BaseComponent {
private myMonitoringService: MyMonitoringService;
constructor() {
// Manually retrieve the monitoring service from the injector
// so that constructor has no dependencies that must be passed in from child
const injector = ReflectiveInjector.resolveAndCreate([
MyMonitoringService
]);
this.myMonitoringService = injector.get(MyMonitoringService);
this.logNavigation();
}
private logNavigation() {
this.myMonitoringService.logPageView();
}
}
These steps should get your application up and running with Application Insights. To read about how to use the metrics being gathered, refer to this article. And, if you want to dig deeper into the API, you can read about using custom events and metrics.
Is there an update for how to make the new @microsoft/applicationinsights-web package with Angular? I see there is a React plugin on the docs page https://docs.microsoft.com/en-us/azure/azure-monitor/app/javascript but there is no mention of Angular.
Himanshu, did you see this page:
https://devblogs.microsoft.com/premier-developer/angular-how-to-add-application-insights-to-an-angular-spa/
Hey this exactly what I am looking for i.e. adding App insights to Angular SPA but unfortunately I dont have Angular experience so finding the above blog difficult to relate. Is there some youtube video or some other detailed steps that I can follow to get this working on my sample app first? As the stpes 7,8 and 10 are little confusing on which class (ts) needs to be modified or created. Can you put...
Here is a demo Angular application that includes the App Insights code: https://github.com/laurieatkinson/ng-patterns-demo It includes many more features, but the code you’ll want to start with is in src/app/framework/logging/logging.service.ts and src/app/framework/components/base-component.ts