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:
A Step-by-Step Guide to Azure Insights Integration with .NET Core API
Streamlining Microsoft Azure Insights Integration with Angular (You’re here!)
Log Request Payloads Using Custom Events in Microsoft Azure Insights
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
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).
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.
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 |
|
---|---|
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) |
Open your Angular application in a terminal.
Run the following command to install the Application Insights SDK:
Code Block | ||
---|---|---|
| ||
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:
Code Block | ||
---|---|---|
| ||
{ "isAzureInsightsEnabled": false, "azureInsightsConnectionString":"ENCRYPTED_INSTRUMENTATION_KEY", "azureInsightsLogLevel": 0, } |
Key | Default Value | Type | Explanation |
---|---|---|---|
|
| Boolean | Indicates whether Azure Insights is enabled. |
|
| 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. |
|
| Integer | Specifies the logging level (0 to 4): |
This table summarizes the JSON configuration with a simple description for each field.
Panel | ||||||||
---|---|---|---|---|---|---|---|---|
| ||||||||
The |
Step 4: Configure Environment-Based Settings
To streamline your integration further, you can configure different Instrumentation Keys for different environments (e.g., development, production).
In your
src/environments/environment.ts
file, add the Instrumentation Key:Code Block language typescript export const environment = { production: false, appInsights: { isAzureInsightsEnabled: false, connectionString: '', logLevel: 03, }, };
In the
src/environments/environment.prod.ts
file, add the production Instrumentation Key:Code Block language typescript export const environment = { production: true, appInsights: { isAzureInsightsEnabled: false, connectionString: '', logLevel: 03, }, };
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.
Create and Define an
AppSettings
Class for Azure Insights Configuration:Code Block language typescript export class AppSettings { isAzureInsightsEnabled!: boolean; azureInsightsLogLevel!: 0 | 1 | 2 | 3 | 4; azureInsightsConnectionString!: string; }
Loading Application Settings from
app-settings.json
into Environment Variables usingAppConfigurationService
:Code Block language typescript 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()}`); } }
Initializing Application Configuration on Startup using
APP_INITIALIZER
withAppConfigurationService
in Angular'sAppModule
Code Block language typescript 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
Open your Angular project in an editor.
Navigate to the
src/app/services/logging
folder, and open or create an Application Insights Service (for example,app-insights.service.ts
).Import and configure Application Insights:
Code Block language typescript 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); } }
Panel | ||||||||
---|---|---|---|---|---|---|---|---|
| ||||||||
Explanation: The AppInsightsService integrates Azure Application Insights into an Angular application for monitoring and telemetry. Here's a simplified explanation:
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.
Open the Component File:
Open the relevant component where telemetry data needs to be tracked (for example,
app.component.ts
or any other component).
Inject the AppInsightsService:
In the component’s TypeScript file, import the
AppInsightsService
and inject it through the constructor.
Code Block | ||
---|---|---|
| ||
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' }); } } |
Panel | ||||||||
---|---|---|---|---|---|---|---|---|
| ||||||||
Explanation: This Angular component integrates with Microsoft Azure Application Insights to monitor and track important events, such as page views, errors, and user interactions.
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. |
Panel | ||||||||
---|---|---|---|---|---|---|---|---|
| ||||||||
Use Step by step instructions to integrate Azure Application Insights with Angular's default error handler for comprehensive exception logging. |
Create a Custom Error Handler
Modify the App Module to Use the Custom Error Handler
Test the Integration
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.
Go to your Application Insights resource in Azure.
Navigate to sections like Live Metrics, Failures, Performance, and Custom Events to see real-time data and insights.
Use these insights to identify performance bottlenecks, errors, and user behavior, and make informed improvements to your application.
Note |
---|
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. |
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.