top of page

Azure Application Insights

Updated: Oct 15, 2021

This blog article shows how to create an Azure Application Insights service and hook it up with your Angular web app and NodeJs server.


Fig 1 - Create Application Insights into Azure and record the "Instrumentation Key"


In the Angular web app install the following libraries:

npm install --save applicationinsights
npm i --save @microsoft/applicationinsights-web

Create a new service

ng generate service AppInsights
import { Injectable } from '@angular/core';
import { ApplicationInsights } from '@microsoft/applicationinsights-web'
import { environment } from 'environments/environment';

@Injectable({
  providedIn: 'root'
})
export class AppInsightsService {

  instance:ApplicationInsights;

 constructor() {

 this.instance = new ApplicationInsights({ config: {
      instrumentationKey: environment.appInsights.instrumentationKey,
      enableAutoRouteTracking: true
 //,enableCorsCorrelation: true     
    } });

 this.instance.loadAppInsights();
 this.instance.trackPageView(); 
   }
}

enableAutoRouteTracking will give you the number of page's views.


enableCorsCorrelation: correlate the request with the operation id. In a nutshell, it allows the request-id header to be passed in the request.


To understand more read this article:



One useful feature you can add to your web app is the ability to distinguish the logged-in user based on their application's roles.


Add the appInsigtsService into the AuthorizationService constructor

export class AuthService 
{
  userAgent:UserAgentApplication;
 
 constructor(private msalService: MsalService, private http: HttpClient, 
 private appInsights: AppInsightsService) 
  {    
 this.userAgent = new UserAgentApplication(MSAL_CONFIGURATION);
  }

Modify the isAuthenticated() method to setAuthenticatedUserContext() passing a user.id and role

 isAuthenticated = async (): Promise<boolean> => {

 let userInfo = this.getUserInfo() as IUser;

 if(userInfo)
 {
   this.appInsights.instance.setAuthenticatedUserContext
   (userInfo.emails[0], userInfo.rolesOnly[0]);
 }
 else
 {
   this.appInsights.instance.clearAuthenticatedUserContext();
 }
 
 return !!this.getUserInfo();
 };

Fig 2 - search by roles and user information

Fig 3 - see the paged viewed by the user in a particular role


On the server-side, do the following:

npm install --save applicationinsights

Inside app.ts file add:


const appInsights = require('applicationinsights');
..................................
  constructor() {
        
        let serverConstants = new ServerConstants();
        serverConstants.initialize();       
       
        this.port = process.env.PORT || 3000;  
        
        process.env["APPINSIGHTS_INSTRUMENTATIONKEY"] = 'af210859-5409-41fa-8e1a-9862bc95ef84';
                
        appInsights.setup();
        const key = appInsights.defaultClient.context.keys.cloudRole;
        appInsights.defaultClient.context.tags[key] = "Agents-Server";
        appInsights.start();
        
        this.app = express();	  

This will change the name of the server on the Azure Insights map diagram:

Fig 4 - components communication map

Fif 5 - click on the server and look at the API requests details


Add code to trace the errors:

  getAllResource(req: any, res: any, next: any): Promise<any> {

    throw new Error('Method not implemented.');

    return this.service
      .getAllResource(req, res, next)
      .then(results => {
        res.json(results);
      })
      .catch(err => {
        let client = appInsights.defaultClient;
        client.trackTrace({message: `Invalid call to getAllResource`, severity: appInsights.Contracts.SeverityLevel.Error});
        console.log(err);
      });
  }

.............................
inside app.ts
  
 start() 
 {       
     this.app.use(this.logErrors);

     this.app.listen(this.port, (err: any) => 
     {
      console.log('Listening on http://localhost:%d', 
      process.env.NODE_ENV, this.port);
     });
}
  
logErrors(err, req, res, next) 
{
 let client = appInsights.defaultClient;
 client.trackTrace({message: `Invalid call`, 
 severity: appInsights.Contracts.SeverityLevel.Error});

 if (err.stack) 
 {
   console.error(err.stack);
   LogErrors.logErrors(err);  
 } 
 
 next(err);
}

Fig 6 - see the code's exceptions



451 views0 comments

Recent Posts

See All

Distributed transactions in the Cloud - part II

Last year I worked on several Cloud integrations between various vendor applications used by an educational institution. These integrations make use of a disconnected architecture where a service bus

Distributed transactions in the Cloud - part I

One of the most common problem that a microservice architecture is facing is performing a transaction across multiple services. A distributed architecture is based on a number of small components, fun

  • Facebook profile
  • Twitter profile
  • LinkedIn Profile

©2020 by PlanetIT. Proudly created with Wix.com

bottom of page