Enabling application insights with containerized dotnet applications

Mon, September 2, 2024 - 2 min read

Application Insights

Application Insights is a feature of Azure Monitor that can provide you insights into your applications performance and help with troubleshooting.

Deploying Application Insights

First off we need to deploy application insights, in this scenario were doing it trough Bicep and IAC and the module can look like this

Application Insights Bicep Module

appi.bicep
param location string
param logAnalyticsWorkspaceId string
param environment string
param solution string
var appInsightsName = 'appi-${environment}-${solution}'
 
resource appInsights 'Microsoft.Insights/components@2020-02-02' = {
  name: appInsightsName
  location: location
  kind: 'web'
  properties: {
    Application_Type: 'web'
    WorkspaceResourceId: logAnalyticsWorkspaceId
  }
}
 
output appInsightsInstrumentationKey string = appInsights.properties.InstrumentationKey
output applicationInsightsId string = appInsights.id

Expose the Application Insights Instrumentation key as an environment variable for Container Apps

main.bicep
 
    secrets: {
      secureList: [
        {
          name: 'applicationinsightsinstrumentationkey'
          value: applicationInsights.outputs.appInsightsInstrumentationKey
        }
      ]
    }
    ######
    ######
        env: [
          {
            name: 'ASPNETCORE_ENVIRONMENT'
            value: ASPNETCORE_ENVIRONMENT
          }
          {
            name: 'TZ'
            value: 'Europe/Oslo'
          }
          {
            name: 'APPLICATIONINSIGHTS_CONNECTION_STRING'
            secretRef: 'applicationinsightsinstrumentationkey'
          }
        ]
 

Add the required package to the application code

In my case i added the NuGet packages using the command:

dotnet add package Microsoft.ApplicationInsights.AspNetCore --version 2.22.0

Add the required code to your dotnet application

Program.cs
 
builder.Services.AddApplicationInsightsTelemetry(); // Add this line of code to enable Application Insights.
builder.Services.AddServiceProfiler(); // Add this line of code to enable Profiler
builder.Services.AddMvc(); // Add this to enable additional services
 

And thats it!

You should not be able to view Application Map like this: alt text Live Metrics: alt text

And much more like applicaton exceptions etc. Thanks for reading and good luck!