Implement Instrumentation in an Application
Application Insights is an Azure monitoring service that tracks the health and performance of your applications. The service collects telemetry data such as request rates, error rates, and response times, which helps you troubleshoot issues and optimize performance. Adding instrumentation early in development gives you visibility into how your app behaves in production.
Setting Up the SDK
To begin monitoring, you install the Application Insights SDK into your project and provide a connection string or instrumentation key. This key tells the SDK where to send the data it collects. Once configured, the SDK automatically gathers requests, dependencies, exceptions, and performance counters without additional code.
Adding Custom Telemetry
Automatic instrumentation covers common scenarios, but you can track more specific data using the TelemetryClient API. The TrackEvent method records business events like button clicks or purchases, while TrackMetric measures performance values such as queue lengths. You can attach properties and metrics to these calls to add context that helps analyze user behavior or application logic.
Verifying Your Implementation
After setup, use Live Metrics in the Azure portal to see real-time data and confirm your app is sending events. Query logs in Log Analytics to explore collected data. If you don't see expected telemetry, check your SDK configuration and sampling settings.
Implement Custom Telemetry and Event Tracking
Custom telemetry lets you track events, metrics, and traces that automatic instrumentation doesn't cover. This is essential for monitoring business-specific activities and user interactions that matter to your organization.
Choosing an Instrumentation Approach
Two methods exist for instrumenting your application. Automatic instrumentation enables telemetry collection through configuration without changing code, making it the easiest path when available. Manual instrumentation involves coding against the Application Insights or OpenTelemetry API, giving you flexibility to capture custom dependencies or API calls not tracked by default. When both methods are used, manual settings take precedence to prevent duplicate data.
Using the TelemetryClient API
The TelemetryClient API provides methods to track custom events, metrics, dependencies, and traces. Each telemetry call can include properties and metrics that add context, making your data easier to filter and analyze.
Enriching and Filtering Data
Telemetry initializers add common properties to all telemetry items, such as application version or user ID. Telemetry processors filter or modify telemetry before it leaves your application, removing sensitive data or reducing noise. This ensures only relevant data is collected, optimizing both performance and cost.
OpenTelemetry Integration
OpenTelemetry is a vendor-neutral standard for collecting telemetry, and Azure Monitor offers an OpenTelemetry Distro that simplifies integration. This distro includes instrumentation libraries for common frameworks that automatically collect traces, metrics, and logs.
Optimize Telemetry through Customization and Data Volume Control
Telemetry optimization involves customizing data collection and controlling volume to manage costs and performance. This uses Telemetry Initializers to enrich data and Telemetry Processors to filter sensitive information, along with sampling strategies.
Telemetry Initializers
Telemetry Initializers add or modify properties across all telemetry data. For example, appending Environment: "Production" to every log entry creates consistent metadata that makes filtering and analysis easier in queries. You implement an initializer by creating a class that implements the ITelemetryInitializer interface and registering it in your configuration.
Telemetry Processors
Telemetry Processors filter specific telemetry items before they are sent to Azure. This removes sensitive data like personal identification or excludes low-value events that create noise. Processors can be chained together to create complex filtering logic.
Sampling Strategies
Sampling controls data volume by collecting only a percentage of telemetry. Fixed-rate sampling lets you specify a percentage, such as 50%, which halves data ingestion. This approach works well for high-traffic applications where full data collection isn't necessary. The key is balancing the rate to retain enough data for accurate analysis while minimizing costs.
Benefits of Optimization
Customizing and controlling telemetry reduces costs associated with data ingestion and storage, improves application performance by minimizing overhead, and enhances data security by filtering sensitive information.
Application Insights requires you to instrument your application by adding code or configuration that collects and sends telemetry data. This involves setting up the SDK and configuring instrumentation to track requests, dependencies, and exceptions.
Adding Application Insights to Your Project
You can add Application Insights automatically through Visual Studio or manually by installing NuGet packages. For ASP.NET and ASP.NET Core applications, Visual Studio's "Add Application Insights Telemetry" option automatically adds required SDK packages and configures your project with a connection string. Without Visual Studio, you manually install packages like Microsoft.ApplicationInsights.AspNetCore and add the AddApplicationInsightsTelemetry() method to your startup code.
Configuring the Connection String
The connection string tells the SDK where to send telemetry data. The recommended method is storing it in your configuration file, such as appsettings.json for ASP.NET Core apps. You can also set it using the environment variable APPLICATIONINSIGHTS_CONNECTION_STRING or directly in code. Keep this string secure and avoid hard-coding it in your application.
Automatic Telemetry Collection
The SDK includes auto collectors that track incoming HTTP requests, outgoing dependencies like database calls, exceptions, and performance counters without additional code. The DependencyTrackingTelemetryModule automatically logs SQL database calls and HTTP endpoint requests. Enabling these modules provides comprehensive monitoring out-of-the-box.
Select and Apply Instrumentation Methods for Diverse Environments
Choosing the right instrumentation method depends on your environment and needs. The right choice ensures you capture essential performance data without unnecessary complexity.
Autoinstrumentation
Autoinstrumentation, also called codeless instrumentation, enables monitoring through the Azure Portal without changing application code. This method works with Azure App Service and supports .NET, Java, and Node.js. It's ideal when you want to avoid instrumentation maintenance and source code modifications. You simply toggle a setting in the portal, and Azure handles the rest.
Manual Instrumentation
Manual instrumentation requires installing a language-specific SDK and coding against the Application Insights or OpenTelemetry API. This approach is necessary when you need to capture custom dependencies or specific API calls not tracked by default. Manual instrumentation gives you more control over what data you collect.
OpenTelemetry
OpenTelemetry is Microsoft's future direction for telemetry collection. It uses instrumentation libraries to capture signals across common frameworks effortlessly. Important concepts include distributed tracing (tracking requests across services), metrics (measuring performance over time), and logs (recording specific events and errors).
Client-Side Monitoring
To monitor the client-side of web applications, use the JavaScript SDK by injecting a script into your HTML header. This tracks user interactions and page performance. Comprehensive monitoring requires both server-side and client-side data to see the full picture of application health.