Automates the integration of Azure Application Insights telemetry into web applications for monitoring, diagnostics, and performance tracking
This skill helps you integrate Azure Application Insights into your applications for comprehensive monitoring and telemetry.
Use this skill when you need to:
Step 1: Add the NuGet Package
dotnet add package Microsoft.ApplicationInsights.AspNetCore
Step 2: Configure in Program.cs
// In Program.cs (ASP.NET Core 6+)
var builder = WebApplication.CreateBuilder(args);
// Add Application Insights telemetry
builder.Services.AddApplicationInsightsTelemetry(options =>
{
options.ConnectionString = builder.Configuration["ApplicationInsights:ConnectionString"];
});
var app = builder.Build();
Step 3: Add Configuration
Add to appsettings.json:
{
"ApplicationInsights": {
"ConnectionString": "InstrumentationKey=your-key;IngestionEndpoint=https://your-region.in.applicationinsights.azure.com/"
},
"Logging": {
"ApplicationInsights": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning"
}
}
}
}
Step 4: Use Custom Telemetry
public class MyService
{
private readonly TelemetryClient _telemetryClient;
public MyService(TelemetryClient telemetryClient)
{
_telemetryClient = telemetryClient;
}
public async Task ProcessOrderAsync(Order order)
{
using var operation = _telemetryClient.StartOperation<RequestTelemetry>("ProcessOrder");
try
{
// Track custom event
_telemetryClient.TrackEvent("OrderProcessing", new Dictionary<string, string>
{
{ "OrderId", order.Id },
{ "CustomerId", order.CustomerId }
});
// Your business logic here
await ProcessOrder(order);
// Track custom metric
_telemetryClient.TrackMetric("OrderValue", order.TotalAmount);
operation.Telemetry.Success = true;
}
catch (Exception ex)
{
_telemetryClient.TrackException(ex);
operation.Telemetry.Success = false;
throw;
}
}
}
Step 1: Install Package
npm install applicationinsights
Step 2: Initialize at Startup
// At the very beginning of your app (before other requires)
const appInsights = require('applicationinsights');
appInsights.setup(process.env.APPLICATIONINSIGHTS_CONNECTION_STRING)
.setAutoDependencyCorrelation(true)
.setAutoCollectRequests(true)
.setAutoCollectPerformance(true, true)
.setAutoCollectExceptions(true)
.setAutoCollectDependencies(true)
.setAutoCollectConsole(true)
.setUseDiskRetryCaching(true)
.setSendLiveMetrics(true)
.start();
const client = appInsights.defaultClient;
module.exports = client;
Step 3: Track Custom Telemetry
const appInsights = require('./appInsights');
async function processOrder(order) {
const startTime = Date.now();
try {
// Track custom event
appInsights.trackEvent({
name: 'OrderProcessing',
properties: {
orderId: order.id,
customerId: order.customerId
}
});
// Your business logic
await handleOrder(order);
// Track metric
const duration = Date.now() - startTime;
appInsights.trackMetric({ name: 'OrderProcessingTime', value: duration });
// Track custom metric
appInsights.trackMetric({ name: 'OrderValue', value: order.totalAmount });
} catch (error) {
// Track exception
appInsights.trackException({ exception: error });
throw error;
}
}
builder.Services.AddApplicationInsightsTelemetry(options =>
{
options.EnableAdaptiveSampling = true;
});
var telemetryInitializer = new CustomTelemetryInitializer();
builder.Services.AddSingleton<ITelemetryInitializer>(telemetryInitializer);
public class OrderMetricsTracker
{
private readonly TelemetryClient _telemetry;
public void TrackOrderCompleted(Order order)
{
_telemetry.TrackEvent("OrderCompleted", new Dictionary<string, string>
{
{ "OrderId", order.Id },
{ "PaymentMethod", order.PaymentMethod },
{ "ShippingCountry", order.ShippingAddress.Country }
});
_telemetry.TrackMetric("OrderRevenue", order.TotalAmount);
_telemetry.TrackMetric("OrderItems", order.Items.Count);
}
}
function trackUserAction(action, details) {
appInsights.trackEvent({
name: `User_${action}`,
properties: {
userId: details.userId,
action: action,
page: details.page,
timestamp: new Date().toISOString()
}
});
}
public async Task<Result> PerformOperationAsync()
{
using var operation = _telemetryClient.StartOperation<DependencyTelemetry>("DatabaseQuery");
operation.Telemetry.Type = "SQL";
operation.Telemetry.Target = "ProductionDB";
try
{
var result = await _database.QueryAsync();
operation.Telemetry.Success = true;
return result;
}
catch (Exception ex)
{
operation.Telemetry.Success = false;
_telemetryClient.TrackException(ex);
throw;
}
}
{
"ApplicationInsights": {
"ConnectionString": "InstrumentationKey=dev-key",
"EnableAdaptiveSampling": false,
"EnableDebugLogger": true
}
}
{
"ApplicationInsights": {
"ConnectionString": "InstrumentationKey=prod-key",
"EnableAdaptiveSampling": true,
"SamplingPercentage": 5.0
}
}