Streamlining Microsoft Azure Insights Integration with Angular
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:
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 |
---|---|---|---|
|
| 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.
The azureInsightsConnectionString
can be encrypted by navigating to Camms.Risk > Administration > Internal Admin > Cryptography.
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:export const environment = { production: false, appInsights: { isAzureInsightsEnabled: false, connectionString: '', logLevel: 3, }, };
In the
src/environments/environment.prod.ts
file, add the production Instrumentation Key:
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:Loading Application Settings from
app-settings.json
into Environment Variables usingAppConfigurationService
:Initializing Application Configuration on Startup using
APP_INITIALIZER
withAppConfigurationService
in Angular'sAppModule
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:
Explanation: The AppInsightsService integrates Azure Application Insights into an Angular application for monitoring and telemetry. Here's a simplified explanation:
Service Initialization:
It injects
AppConfigurationService
andCammsCryptoService
to load the app's configuration and handle encryption.The
loadAzureInsightConfig()
method is called to configure Application Insights using settings fromapp-settings.json
.
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.
Custom Telemetry Properties:
The service adds default telemetry properties, such as platform ("Web") and application name, to all tracked data.
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.
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.
Explanation: This Angular component integrates with Microsoft Azure Application Insights to monitor and track important events, such as page views, errors, and user interactions.
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.
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.
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.
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.
Create a Custom Error Handler
AppErrorHandlerService
: This service implements Angular'sErrorHandler
interface. When an unhandled error occurs, it will automatically log the exception to Azure Application Insights usingAppInsightsService
.
Modify the App Module to Use the Custom Error Handler
This ensures that Angular uses the
AppErrorHandlerService
for global error handling.
Test the Integration
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.
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.
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.