Azure Application Insights

Azure Application Insights logo

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

The Aspire Azure Application Insights hosting integration models the Application Insights component as the following type:

  • AzureApplicationInsightsResource: Represents an Azure Application Insights resource.

To access this type and APIs, add the 📦 Aspire.Hosting.Azure.ApplicationInsights NuGet package to your AppHost project.

Install the NuGet package
dotnet add package Aspire.Hosting.Azure.ApplicationInsights

Add Azure Application Insights resource

In your AppHost project, call 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...

The preceding code:

  • Adds an Azure Application Insights resource named app-insights to the application model.
  • Automatically creates a Log Analytics workspace to store the telemetry data.
  • References the Application Insights resource in the ExampleProject, making the connection string available.

Caution

When you call AddAzureApplicationInsights, it implicitly calls AddAzureProvisioning—which adds support for generating Azure resources dynamically during app startup. The app must configure the appropriate subscription and location. For more information, see Local provisioning: Configuration.

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...

The preceding code:

  • Adds an Azure Log Analytics workspace resource named log-analytics.
  • Adds an Azure Application Insights resource named app-insights that uses the specified Log Analytics workspace.
  • References the Application Insights resource in the ExampleProject.

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...

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

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 Bicep 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.ConnectionString

The 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 and is influenced by changes to the provisioning infrastructure in C#. Customizations to the Bicep file directly will be overwritten, so make changes through the C# provisioning APIs to ensure they are reflected in the generated files.

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. For example, you can configure the application type, retention settings, and more. The following example demonstrates how to customize the Azure Application Insights resource:

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);

The preceding code:

  • Chains a call to the ConfigureInfrastructure API:
    • The infra parameter is an instance of the AzureResourceInfrastructure type.
    • The provisionable resources are retrieved by calling GetProvisionableResources.
    • The ApplicationInsightsComponent is configured with 90-day retention and a custom tag.

For more information, see Customize Azure resources. For the full list of configurable properties, see the Azure.Provisioning.ApplicationInsights API documentation.

Client integration

Note

The Azure Application Insights hosting integration works with the standard Application Insights SDK and OpenTelemetry exporters. No separate Aspire client integration is required.

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 will automatically pick 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");
    });

See also