Azure Application Insights
This article is the reference for the Aspire Azure Application Insights integration. It covers the AppHost APIs — with examples for both AppHost.cs and apphost.ts — that you use to model an Azure Application Insights resource in your AppHost project, as well as how to configure the Application Insights SDK in consuming apps.
Azure Application Insights is an extensible Application Performance Management (APM) service for developers and DevOps professionals. The Aspire Azure Application Insights integration enables you to provision Application Insights resources for collecting telemetry data from your applications.
Hosting integration
Section titled “Hosting integration”The Aspire Azure Application Insights hosting integration models the Application Insights component as the following type:
AzureApplicationInsightsResource: Represents an Azure Application Insights resource.
Installation
Section titled “Installation”To start building an Aspire app that uses Azure Application Insights, install the 📦 Aspire.Hosting.Azure.ApplicationInsights NuGet package:
aspire add azure-application-insightsLearn more about aspire add in the command reference.
Or, choose a manual installation approach:
#:package Aspire.Hosting.Azure.ApplicationInsights@*<PackageReference Include="Aspire.Hosting.Azure.ApplicationInsights" Version="*" />aspire add azure-application-insightsLearn more about aspire add in the command reference.
This updates your aspire.config.json with the Azure Application Insights hosting integration package:
{ "packages": { "Aspire.Hosting.Azure.ApplicationInsights": "*" }}Add Azure Application Insights resource
Section titled “Add Azure Application Insights resource”Once you’ve installed the hosting integration in your AppHost project, call AddAzureApplicationInsights (or addAzureApplicationInsights) to add and return an Azure Application Insights resource builder:
var builder = DistributedApplication.CreateBuilder(args);
var appInsights = builder.AddAzureApplicationInsights("app-insights");
builder.AddProject<Projects.ExampleProject>() .WithReference(appInsights);
// After adding all resources, run the app...builder.Build().Run();import { createBuilder } from './.modules/aspire.js';
const builder = await createBuilder();
const appInsights = await builder.addAzureApplicationInsights("app-insights");
await builder.addNodeApp("api", "./api", "index.js") .withReference(appInsights);
// After adding all resources, run the app...await builder.build().run();-
An Azure Application Insights resource named
app-insightsis added to the application model. -
A Log Analytics workspace is automatically created to store the telemetry data.
-
The
WithReference(orwithReference) call configures a connection in the consuming project, making the Application Insights connection string available as theAPPLICATIONINSIGHTS_CONNECTION_STRINGenvironment variable.
Use with existing Log Analytics workspace
Section titled “Use with existing Log Analytics workspace”If you have an existing Log Analytics workspace that you want to use, you can link Application Insights to it:
var builder = DistributedApplication.CreateBuilder(args);
var logAnalytics = builder.AddAzureLogAnalyticsWorkspace("log-analytics");var appInsights = builder.AddAzureApplicationInsights("app-insights", logAnalytics);
builder.AddProject<Projects.ExampleProject>() .WithReference(appInsights);
// After adding all resources, run the app...builder.Build().Run();import { createBuilder } from './.modules/aspire.js';
const builder = await createBuilder();
const logAnalytics = await builder.addAzureLogAnalyticsWorkspace("log-analytics");const appInsights = await builder.addAzureApplicationInsights("app-insights", logAnalytics);
await builder.addNodeApp("api", "./api", "index.js") .withReference(appInsights);
// After adding all resources, run the app...await builder.build().run();The preceding code:
- Adds an Azure Log Analytics workspace resource named
log-analytics. - Adds an Azure Application Insights resource named
app-insightsthat uses the specified Log Analytics workspace. - References the Application Insights resource in the consuming project.
Configure Log Analytics workspace after creation
Section titled “Configure Log Analytics workspace after creation”You can also configure the Log Analytics workspace using the fluent API:
var builder = DistributedApplication.CreateBuilder(args);
var logAnalytics = builder.AddAzureLogAnalyticsWorkspace("log-analytics");var appInsights = builder.AddAzureApplicationInsights("app-insights") .WithLogAnalyticsWorkspace(logAnalytics);
builder.AddProject<Projects.ExampleProject>() .WithReference(appInsights);
// After adding all resources, run the app...builder.Build().Run();import { createBuilder } from './.modules/aspire.js';
const builder = await createBuilder();
const logAnalytics = await builder.addAzureLogAnalyticsWorkspace("log-analytics");const appInsights = await builder.addAzureApplicationInsights("app-insights") .withLogAnalyticsWorkspace(logAnalytics);
await builder.addNodeApp("api", "./api", "index.js") .withReference(appInsights);
// After adding all resources, run the app...await builder.build().run();Connection properties
Section titled “Connection properties”The Azure Application Insights resource exposes the following connection property:
| Property name | Description |
|---|---|
appInsightsConnectionString | The connection string for Application Insights. |
This connection string is automatically made available to referencing projects as an environment variable named APPLICATIONINSIGHTS_CONNECTION_STRING (or based on the resource name).
Provisioning-generated Bicep
Section titled “Provisioning-generated Bicep”If you’re new to Bicep, it’s a domain-specific language for defining Azure resources. With Aspire, you don’t need to write Bicep by hand — the provisioning APIs generate it for you. When you publish your app, the generated Bicep is output alongside the manifest file. When you add an Azure Application Insights resource, the following Bicep is generated:
@description('The location for the resource(s) to be deployed.')param location string = resourceGroup().location
param applicationType string = 'web'
param kind string = 'web'
param logAnalyticsWorkspaceId string
resource app_insights 'Microsoft.Insights/components@2020-02-02' = { name: take('app-insights-${uniqueString(resourceGroup().id)}', 260) kind: kind location: location properties: { Application_Type: applicationType WorkspaceResourceId: logAnalyticsWorkspaceId } tags: { 'aspire-resource-name': 'app-insights' }}
output appInsightsConnectionString string = app_insights.properties.ConnectionStringThe preceding Bicep provisions an Azure Application Insights component linked to a Log Analytics workspace for storing telemetry data.
The generated Bicep is a starting point that reflects the provisioning infrastructure configured in your AppHost. Customizations made directly to the Bicep files are overwritten on the next publish — make changes through the C# or TypeScript provisioning APIs instead.
Customize provisioning infrastructure
Section titled “Customize provisioning infrastructure”All Aspire Azure resources are subclasses of the AzureProvisioningResource type. This type enables the customization of the generated Bicep by providing a fluent API to configure the Azure resources using the ConfigureInfrastructure API:
var builder = DistributedApplication.CreateBuilder(args);
var appInsights = builder.AddAzureApplicationInsights("app-insights") .ConfigureInfrastructure(infra => { var insights = infra.GetProvisionableResources() .OfType<ApplicationInsightsComponent>() .Single();
insights.RetentionInDays = 90; insights.IngestionMode = ComponentIngestionMode.LogAnalytics; insights.Tags.Add("environment", "production"); });
builder.AddProject<Projects.ExampleProject>() .WithReference(appInsights);
// After adding all resources, run the app...builder.Build().Run();import { createBuilder } from './.modules/aspire.js';
const builder = await createBuilder();
const appInsights = await builder.addAzureApplicationInsights("app-insights") .configureInfrastructure(async (infra) => { await infra.addParameter("retentionInDays", "90"); await infra.addParameter("environment", "production"); });
await builder.addNodeApp("api", "./api", "index.js") .withReference(appInsights);
// After adding all resources, run the app...await builder.build().run();The preceding C# code:
- Chains a call to the
ConfigureInfrastructureAPI:- The
infraparameter is an instance of theAzureResourceInfrastructuretype. - The provisionable resources are retrieved by calling
GetProvisionableResources. - The
ApplicationInsightsComponentis configured with 90-day retention and a custom tag.
- The
For more information, see Customize Azure resources. For the full list of configurable properties, see the Azure.Provisioning.ApplicationInsights API documentation.
Client integration
Section titled “Client integration”Configure Application Insights in your application
Section titled “Configure Application Insights in your application”To use Application Insights in your application, configure the OpenTelemetry exporter in your service defaults:
public static IHostApplicationBuilder AddServiceDefaults( this IHostApplicationBuilder builder){ builder.ConfigureOpenTelemetry();
// ... other configuration
return builder;}
public static IHostApplicationBuilder ConfigureOpenTelemetry( this IHostApplicationBuilder builder){ builder.Logging.AddOpenTelemetry(logging => { logging.IncludeFormattedMessage = true; logging.IncludeScopes = true; });
builder.Services.AddOpenTelemetry() .WithMetrics(metrics => { metrics.AddAspNetCoreInstrumentation() .AddHttpClientInstrumentation() .AddRuntimeInstrumentation(); }) .WithTracing(tracing => { tracing.AddSource(builder.Environment.ApplicationName) .AddAspNetCoreInstrumentation() .AddHttpClientInstrumentation(); });
builder.AddOpenTelemetryExporters();
return builder;}
private static IHostApplicationBuilder AddOpenTelemetryExporters( this IHostApplicationBuilder builder){ var useOtlpExporter = !string.IsNullOrWhiteSpace( builder.Configuration["OTEL_EXPORTER_OTLP_ENDPOINT"]);
if (useOtlpExporter) { builder.Services.AddOpenTelemetry() .UseOtlpExporter(); }
// Application Insights automatically picks up the connection string // from the APPLICATIONINSIGHTS_CONNECTION_STRING environment variable.
return builder;}Alternatively, you can use the Azure Monitor OpenTelemetry exporter directly:
builder.Services.AddOpenTelemetry() .UseAzureMonitor(options => { options.ConnectionString = builder.Configuration .GetConnectionString("app-insights"); });