Skip to end of metadata
Go to start of metadata

You are viewing an old version of this content. View the current version.

Compare with Current View Version History

« Previous Version 9 Next »

Welcome to the third part of our Microsoft Azure Insights Integration documentation series! This series will guide you through various aspects of integrating Azure Insights across different technologies and platforms. Below is an overview of the topics covered in this series:

  1. Getting Started with Microsoft Azure Insights Integration

  2. A Step-by-Step Guide to Azure Insights Integration with .NET Core API

  3. Streamlining Microsoft Azure Insights Integration with Angular (You’re here!)

  4. Log Request Payloads Using Custom Events in Microsoft Azure Insights

  5. Tracking Response Exceptions via Custom Event Logging in Azure Insights

In this third part, we will focus on streamlining the integration of Azure Insights within Angular applications for front-end monitoring and logging.


This guide explains how to integrate Microsoft Azure Application Insights into an Angular application. By doing so, we can monitor, diagnose, and gather critical insights into the performance and user interactions of the frontend, helping to ensure a smooth and responsive user experience.

Prerequisites

  • Angular Application: Frontend built using Angular (minimum version 11 or higher).

  • Azure Subscription: Access to Microsoft Azure services.

  • Azure Application Insights SDKs: For JavaScript/TypeScript.

  • Basic knowledge of Application Insights: Familiarity with logging and telemetry.


Step 1: Set Up Application Insights in Azure

  1. Create Application Insights Resource in Azure:

    • Log in to your Azure Portal.

    • Navigate to Application Insights and create a new resource.

    • Provide a name, select the appropriate subscription and resource group, and set your region (choose the region closest to your application's hosting).

    • Once the resource is created, go to the Overview page and copy the Instrumentation Key (this will be needed for both backend and frontend integration).

  2. Configure Role-Based Access Control (RBAC):

    • Ensure that the appropriate permissions are granted for accessing the telemetry data. Add necessary users or service accounts with read or contributor access.

image-20241001-080213.png

Step 2: Install Application Insights JavaScript SDK

Azure Application Insights provides a npm package for integrating with web applications. To install it in your Angular application, follow these steps:

Angular Version

@microsoft/applicationinsights-web Package Version

Angular 12

v2.x

Angular 13

v2.x

Angular 14

v2.x

Angular 15

v2.x

Angular 16

v3.x (Latest)

Angular 17

v3.x (Latest)

  1. Open your Angular application in a terminal.

  2. Run the following command to install the Application Insights SDK:

npm install @microsoft/applicationinsights-web

Step 3: Adding New Configurations to app-settings.json

In your src/assets/settings/app-settings.json, add the Instrumentation Key, a feature flag to enable or disable the functionality and log level configuration:

{
  "isAzureInsightsEnabled": false,
  "azureInsightsConnectionString":"ENCRYPTED_INSTRUMENTATION_KEY",
  "azureInsightsLogLevel": 0,
}

Key

Default Value

Type

Explanation

isAzureInsightsEnabled

false

Boolean

Indicates whether Azure Insights is enabled. false means it is currently disabled.

azureInsightsConnectionString

"ENCRYPTED_CONNECTION_STRING"

String

The encrypted connection string used to securely connect to Azure Insights. This string is encrypted using cryptographic methods to ensure the security and confidentiality of the connection details.

azureInsightsLogLevel

3

Integer

Specifies the logging level (0 to 4):
0: Verbose (detailed logs)
1: Information
2: Warning
3: Error
4: Critical (most severe).

This table summarizes the JSON configuration with a simple description for each field.

The azureInsightsConnectionString can be encrypted by navigating to Camms.Risk > Administration > Internal Admin > Cryptography.

image-20241009-013523.png

Step 4: Configure Environment-Based Settings

To streamline your integration further, you can configure different Instrumentation Keys for different environments (e.g., development, production).

  1. In your src/environments/environment.ts file, add the Instrumentation Key:

    export const environment = {
      production: false,
      appInsights: {
          isAzureInsightsEnabled: false,
          connectionString: '',
          logLevel: 3,
      },
    };
  2. In the src/environments/environment.prod.ts file, add the production Instrumentation Key:

    export const environment = {
      production: true,
      appInsights: {
          isAzureInsightsEnabled: false,
          connectionString: '',
          logLevel: 3,
      },
    };

Step 5: Mapping app-settings.json Configuration to Environment Variables

Map values from app-settings.json to environment variables to enhance security and flexibility. This allows dynamic configuration without hardcoding sensitive data across different environments.

  1. Create and Define an AppSettings Class for Azure Insights Configuration:

    export class AppSettings {
        isAzureInsightsEnabled!: boolean;
        azureInsightsLogLevel!: 0 | 1 | 2 | 3 | 4;
        azureInsightsConnectionString!: string;
    }
  2. Loading Application Settings from app-settings.json into Environment Variables using AppConfigurationService:

    import { HttpClient } from "@angular/common/http";
    import { Injectable } from "@angular/core";
    import { environment } from "@environments/environment";
    import { AppConfiguration, AppSettings } from "@models";
    import { Observable, lastValueFrom } from "rxjs";
    import { tap } from "rxjs/operators";
    
    @Injectable({
        providedIn: 'root'
    })
    
    export class AppConfigurationService {
        private readonly APP_SETTING_URL = 'assets/settings/app-settings.json';
    
        constructor(private http: HttpClient) { }
    
        public async loadAppSettings(): Promise<any> {
            return lastValueFrom(this.getAppSettingsFromJson().pipe(tap((configuration: AppSettings) => {
                environment.appInsights.isAzureInsightsEnabled = configuration.isAzureInsightsEnabled
                environment.appInsights.logLevel = configuration.azureInsightsLogLevel
                environment.appInsights.connectionString = configuration.azureInsightsConnectionString          
            })));
        }
    
        private getAppSettingsFromJson(): Observable<AppSettings> {
            return this.http.get<AppSettings>(`${this.APP_SETTING_URL}?v=${new Date().getUTCMilliseconds()}`);
        }
    }
  3. Initializing Application Configuration on Startup using APP_INITIALIZER with AppConfigurationService in Angular's AppModule

    import { APP_INITIALIZER, NgModule } from '@angular/core';
    import { AppConfigurationService } from '@services';
    import { AppComponent } from './app.component';
    
    @NgModule({
      declarations: [],
      imports: [],
      providers: [
        {
          provide: APP_INITIALIZER,
          useFactory: (configService: AppConfigurationService) => () => configService.loadAppSettings(),
          deps: [AppConfigurationService],
          multi: true
        },
      ],
      bootstrap: [AppComponent]
    })
    
    export class AppModule { }

Step 6: Configure Application Insights in Angular

  1. Open your Angular project in an editor.

  2. Navigate to the src/app/services/logging folder, and open or create an Application Insights Service (for example, app-insights.service.ts).

  3. Import and configure Application Insights:

    import { Injectable } from '@angular/core';
    import { environment } from '@environments/environment';
    import { ApplicationInsights, ITelemetryItem } from '@microsoft/applicationinsights-web';
    import { AppConfigurationService } from '@services/app-configuration.service';
    import { CammsCryptoService } from '@services/camms-crypto.service';
    
    @Injectable({
      providedIn: 'root',
    })
    export class AppInsightsService {
      appInsights: ApplicationInsights = {} as ApplicationInsights;
    
      constructor(private appConfigurationService: AppConfigurationService) {
        this.loadAzureInsightConfig();
      }
      
      private loadAzureInsightConfig() {
        this.appConfigurationService.loadAppSettings().then(() => {
          if (environment.appInsights.isAzureInsightsEnabled) {
            this.appInsights = new ApplicationInsights({
              config: {
                enableCorsCorrelation: true,
                enableAutoRouteTracking: true,
                connectionString: CammsCryptoService.getDecryptedKeyValue(environment.appInsights.connectionString),
                loggingLevelConsole: environment.appInsights.logLevel,
                loggingLevelTelemetry: environment.appInsights.logLevel,
              }
            });
    
            this.appInsights.loadAppInsights();
            this.loadCustomTelemetryProperties();
          }
        });
      }
      
      private loadCustomTelemetryProperties() {
        this.appInsights.addTelemetryInitializer((envelope: ITelemetryItem) => {
          var item = envelope.baseData;
          if (item) {
            item["properties"] = item["properties"] || {};
            item["properties"]["ApplicationPlatform"] = "Web";
            item["properties"]["ApplicationName"] = "APPLICATION_NAME";
          }
        });
      }
    
      logPageView(name?: string, url?: string) {
        this.appInsights.trackPageView({ name: name, uri: url });
      }
    
      logEvent(name: string, properties?: { [key: string]: any }) {
        this.appInsights.trackEvent({ name: name }, properties);
      }
    
      logMetric(name: string, average: number, properties?: { [key: string]: any }) {
        this.appInsights.trackMetric({ name: name, average: average }, properties);
      }
    
      logException(exception: Error, severityLevel?: number) {
        this.appInsights.trackException({ exception: exception, severityLevel: severityLevel });
      }
    
      logTrace(message: string, properties?: { [key: string]: any }) {
        this.appInsights.trackTrace({ message: message }, properties);
      }
    }

Explanation: The AppInsightsService integrates Azure Application Insights into an Angular application for monitoring and telemetry. Here's a simplified explanation:

  1. Service Initialization:

    • It injects AppConfigurationService and CammsCryptoService to load the app's configuration and handle encryption.

    • The loadAzureInsightConfig() method is called to configure Application Insights using settings from app-settings.json.

  2. Loading Configuration:

    • The service checks if Azure Insights is enabled. If so, it initializes Application Insights with settings like CORS tracking, automatic route tracking, and a decrypted connection string.

    • The service loads these settings and starts Application Insights.

  3. Custom Telemetry Properties:

    • The service adds default telemetry properties, such as platform ("Web") and application name, to all tracked data.

  4. Logging Methods:

    • The service provides methods for logging page views, events, metrics, exceptions, and traces to Application Insights.

In essence, AppInsightsService configures Application Insights, adds custom telemetry properties, and provides methods for logging telemetry data securely.


Step 7: Integrate Application Insights into Angular Components

Once the Application Insights service is configured, it can be integrated into any Angular component to track telemetry data, such as page views, exceptions, and custom events.

  1. Open the Component File:

    • Open the relevant component where telemetry data needs to be tracked (for example, app.component.ts or any other component).

  2. Inject the AppInsightsService:

    • In the component’s TypeScript file, import the AppInsightsService and inject it through the constructor.

import { Component, OnInit } from '@angular/core';
import { AppInsightsService } from '@services/app-insights.service';

@Component({
  selector: 'app-component',
  templateUrl: './component.component.html',
  styleUrls: ['./component.component.css'],
})
export class Component implements OnInit {
  constructor(private appInsightsService: AppInsightsService) {}

  ngOnInit() {
    this.appInsightsService.logPageView('ComponentPage');
  }

  handleError(error: Error) {
    this.appInsightsService.logException(error);
  }

  trackUserAction() {
    this.appInsightsService.logEvent('UserAction', { action: 'ClickedButton' });
  }
}

Explanation: This Angular component integrates with Microsoft Azure Application Insights to monitor and track important events, such as page views, errors, and user interactions.

  1. Imports and Setup:

    • The component imports a service, AppInsightsService, which is responsible for communicating with Azure Application Insights.

    • This service is injected into the component, making it available for use.

  2. Page View Logging:

    • When the component is initialized, it automatically logs a page view using Azure Application Insights. This helps track when users visit or interact with that particular part of the application.

  3. Error Logging:

    • The component has a method for logging errors. If an error occurs, this method sends the error details to Application Insights, helping with monitoring and debugging.

  4. Custom Event Tracking:

    • The component can also track specific user actions, such as button clicks. This custom event is logged, allowing detailed insight into how users are interacting with the app.

In summary, this component is designed to log key information (page views, errors, and user actions) to Azure Application Insights, improving the monitoring and troubleshooting of the application.


Use Step by step instructions to integrate Azure Application Insights with Angular's default error handler for comprehensive exception logging.

  1. Create a Custom Error Handler

import { ErrorHandler, Injectable } from '@angular/core';
import { AppInsightsService } from './app-insights.service';

@Injectable({
  providedIn: 'root',
})
export class AppErrorHandlerService implements ErrorHandler {
  constructor(private appInsightsService: AppInsightsService) {}

  handleError(error: any): void {
    this.appInsightsService.logException(error);
    console.error('An error occurred:', error);
  }
}
  • AppErrorHandlerService: This service implements Angular's ErrorHandler interface. When an unhandled error occurs, it will automatically log the exception to Azure Application Insights using AppInsightsService.

  1. Modify the App Module to Use the Custom Error Handler

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppComponent } from './app.component';
import { AppErrorHandlerService } from '@services/app-error-handler.service';
import { ErrorHandler } from '@angular/core';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule
  ],
  providers: [
    { provide: ErrorHandler, useClass: AppErrorHandlerService }
  ],
  bootstrap: [AppComponent]
})
export class AppModule { }
  • This ensures that Angular uses the AppErrorHandlerService for global error handling.

  1. Test the Integration

ngOnInit() {
  throw new Error('Test error for Application Insights');
}

To ensure everything works as expected:

  • Introduce an intentional error in any component (e.g., app.component.ts).

  • When the app runs, this error should be logged automatically to Azure Application Insights, and the details can be viewed in the Azure portal under Failures.


Step 7: Monitor Telemetry Data in Azure

Once your application is live and users begin interacting with it, you can monitor telemetry data in the Azure portal.

  1. Go to your Application Insights resource in Azure.

  2. Navigate to sections like Live Metrics, Failures, Performance, and Custom Events to see real-time data and insights.

    image-20241009-021029.png
  3. Use these insights to identify performance bottlenecks, errors, and user behavior, and make informed improvements to your application.

    image-20241009-021255.png

To view frontend application insights data, please ensure that the Browser toggle is selected instead of Server. This will enable visibility of telemetry related to client-side activities such as user interactions, page views, and JavaScript errors.

image-20241009-021602.png

Conclusion

In this guide, we've covered the process of integrating Microsoft Azure Application Insights with an Angular application. By implementing this integration, you can monitor key metrics such as page views, custom events, and exceptions, providing valuable insights into your application's frontend performance and user behavior. Additionally, by configuring the default error handler, all uncaught exceptions are automatically logged, simplifying troubleshooting and enhancing the overall health of the application. This setup ensures proactive monitoring and allows for data-driven improvements in your Angular application.

  • No labels