Skip to main content

Trace a request into Application Insights

Deploy an ASP.NET Core app, generate a handled exception and an HTTP dependency, and follow them into Application Insights (Azure Monitor's application performance monitoring feature) using the app's managed identity. This is app-owned OpenTelemetry, not automatic APM.

Billable resources

This creates billable resources (Azure Monitor pricing); use synthetic inputs only. The workspace has 30-day retention and a 0.1 GB/day ingestion cap (caps can overshoot). Anyone who can reach the app can use its controls (two concurrent operations, twelve per minute per process).

How it works​

Application Insights: correlation starts in app code
  1. Instrument an operation

    The server SDK records the request, HTTP dependency, handled exception, and traces with operation and parent IDs.

  2. Authenticate ingestion

    The SDK uses an explicit managed-identity credential. The connection string selects telemetry routing; it is not authentication.

  3. Follow the same operation

    Query the workspace-backed Application Insights data. Match the request, dependency, and exception by operation ID rather than relying on a dashboard shell.

Permission: grant the app identity Monitoring Metrics Publisher on the Application Insights resource. Builder does not install or activate an exporter for your application.

This is the sample's app-owned SDK path, not stdout export through a DCR. Verify actual correlated records after generating an approved synthetic operation.

Your application owns the SDK instrumentation. Builder adds no automatic application performance monitoring (APM), and a connection-string variable alone does not create an exporter. This is separate from runtime log export.

To add this to your own app:

  1. Enable a managed identity on the app and deploy; record its principal ID.
  2. Assign Monitoring Metrics Publisher to that principal at the Application Insights resource scope, never Contributor or Owner.
  3. Configure a server-side SDK that supports Microsoft Entra ingestion, such as the Azure Monitor OpenTelemetry distribution, with the connection string and an explicit managed-identity credential. The connection string is not authentication.
  4. After confirming SDK support, set DisableLocalAuth: true on the component.
  5. Capture requests, dependencies, traces, and exceptions server-side, keeping operation and parent IDs, and redact sensitive URLs, headers, bodies, and user identifiers before export.

Store routing in Connections, never in source or browser assets. Saved connections apply to the next version you deploy. Don't fix identity errors by enabling key-based ingestion.

On an updated target, the Application Insights connection profile can export the same APPLICATIONINSIGHTS_CONNECTION_STRING at runtime. Avoid a duplicate manual entry for that exact name and keep TELEMETRY_MODE and SAMPLE_EXPIRES_AT as separate sample settings. The connection string is routing metadata; selecting an identity and saving it does not install an exporter, grant ingestion access or verify delivery. The deployed catalog advertises this profile; named delivery qualification is separate from configuration support and does not replace the resource grants and correlated telemetry verification in this tutorial.

Prerequisites​

  • An approved development/test subscription in West US 2 (westus2).
  • Permission to create the resources and assign roles, plus query access to the new workspace (such as Log Analytics Reader).
  • The latest Builder CLI release, Node.js 22 or later, Azure CLI with Bicep, Git, and Bash. No local .NET SDK.
  • Public outbound connectivity to Azure Monitor (private endpoints need separate planning).

1. Get the sample and sign in​

Clone the sample:

git clone https://github.com/AzureAppService/app-service-builder-application-insights.git
cd app-service-builder-application-insights

builder --version
builder login
builder account show

Sign in with the Entra account for your subscription. If you previously selected a custom ARM endpoint, reset it:

builder config reset --endpoint-resource-manager

2. Create the app and monitoring resources​

infra/sample.bicep creates the app without source (so its identity exists before selecting it in a connection): a system-assigned identity with resource-scoped Monitoring Metrics Publisher, a workspace-based component with DisableLocalAuth: true, and separate variables TELEMETRY_MODE=managed-identity and SAMPLE_EXPIRES_AT. Don't apply it over existing resources. Save routing through Connections after these app identity identifiers have committed, not in the initial app creation.

Choose fresh names, then preview the changes:

SUBSCRIPTION="<confirmed-subscription-id>"
TENANT="<confirmed-tenant-id>"
LOCATION="westus2"
RG="rg-builder-appinsights-demo"
APP="builder-appinsights-demo"
WORKSPACE="law-builder-appinsights-demo"
APPINSIGHTS="appi-builder-appinsights-demo"
# Choose an absolute UTC time about two hours ahead; do not use this placeholder.
EXPIRES_AT="<yyyy-MM-ddTHH:mm:ssZ>"

az login --tenant "$TENANT"
az group create --subscription "$SUBSCRIPTION" --name "$RG" --location "$LOCATION"
az resource list --subscription "$SUBSCRIPTION" --resource-group "$RG" \
--query "[].{name:name,type:type,id:id}" --output table
az deployment group what-if --subscription "$SUBSCRIPTION" \
--resource-group "$RG" --name sample-resources \
--template-file infra/sample.bicep \
--parameters appName="$APP" workspaceName="$WORKSPACE" \
applicationInsightsName="$APPINSIGHTS" expiresAt="$EXPIRES_AT"

Stop if the group isn't empty and exclusively yours. Review the what-if output, then provision:

az deployment group create --subscription "$SUBSCRIPTION" \
--resource-group "$RG" --name sample-resources \
--template-file infra/sample.bicep \
--parameters appName="$APP" workspaceName="$WORKSPACE" \
applicationInsightsName="$APPINSIGHTS" expiresAt="$EXPIRES_AT" --output none

APP_PRINCIPAL_ID=$(az deployment group show --subscription "$SUBSCRIPTION" \
--resource-group "$RG" --name sample-resources \
--query properties.outputs.appPrincipalId.value --output tsv)
APPINSIGHTS_ID=$(az deployment group show --subscription "$SUBSCRIPTION" \
--resource-group "$RG" --name sample-resources \
--query properties.outputs.applicationInsightsResourceId.value --output tsv)
WORKSPACE_ID=$(az deployment group show --subscription "$SUBSCRIPTION" \
--resource-group "$RG" --name sample-resources \
--query properties.outputs.workspaceResourceId.value --output tsv)

Role propagation can take a few minutes. After the SAMPLE_EXPIRES_AT deadline, demo POSTs return 410; resources aren't deleted.

In Connections, add Application Insights, select this component and the app's system-assigned Managed identity, and retain APPLICATIONINSIGHTS_CONNECTION_STRING as the runtime routing mapping. Do not also declare it as a manual variable. For an older variables-based app, save removal of that manual entry without deploying, then save the connection and deploy the complete configuration once. The Builder CLI procedure, with a release that includes app connections, or Azure CLI/ARM can save the same complete appInsights object under the app ETag. Use the ZIP deployment command below separately to apply source and configuration.

3. Deploy local ZIP source​

Archive the tracked sample source:

git archive --format=zip --output=../application-insights-source.zip HEAD
builder app deploy --name "$APP" --subscription "$SUBSCRIPTION" \
--resource-group "$RG" --source-archive ../application-insights-source.zip \
--manifest ./builder.yaml --json

The manifest must be byte-identical to builder.yaml in the ZIP. Expect status: "Succeeded"; if interrupted, run builder app status "<operation-url>" --wait --json instead of redeploying.

Get the runtime URL:

builder app show --name "$APP" --subscription "$SUBSCRIPTION" \
--resource-group "$RG" --json

Connections and variables are captured per version, so redeploy after changing them. Keep AZURE_CLIENT_ID unset; the exporter uses ManagedIdentityCredential with no key fallback.

4. Verify correlated telemetry​

Open the runtime URL and use each control once; HTTP 500 from Intentional error is an expected handled exception. From a terminal:

APP_URL="<returned-app-runtime-url>"
curl --fail --silent --show-error "$APP_URL/health"
curl --silent --show-error -X POST "$APP_URL/api/demo/error"
curl --fail --silent --show-error -X POST "$APP_URL/api/demo/dependency"

Save the two operationId values, then query your new Log Analytics workspace > Logs:

let ErrorOperation = "<error-operation-id>";
let DependencyOperation = "<dependency-operation-id>";
union withsource=Signal AppRequests, AppExceptions, AppTraces, AppDependencies
| where TimeGenerated > ago(30m)
| where OperationId in (ErrorOperation, DependencyOperation)
| project TimeGenerated, Signal, OperationId, ParentId,
Id = column_ifexists("Id", ""),
Name = column_ifexists("Name", ""),
Message = column_ifexists("Message", ""),
ExceptionType = column_ifexists("ExceptionType", ""),
ResultCode = column_ifexists("ResultCode", "")
| order by TimeGenerated asc

Expect a failed 500 request, SyntheticDemoException, and a trace for the error operation, and a request, GET loopback catalog dependency, child request, and trace for the dependency operation. Ingestion can take up to ten minutes.

Check authentication settings:

az resource show --ids "$APPINSIGHTS_ID" --api-version 2020-02-02 \
--query properties.DisableLocalAuth --output tsv
az role assignment list --subscription "$SUBSCRIPTION" --scope "$APPINSIGHTS_ID" \
--query "[?principalId=='$APP_PRINCIPAL_ID' && roleDefinitionName=='Monitoring Metrics Publisher'].{scope:scope,principalId:principalId,role:roleDefinitionName}"

Expect true and the app principal's role.

5. Troubleshoot missing signals​

SymptomCheck
App serves requests, no recordsActive version, exporter, connection string, query window and workspace
Credential acquisition failsDeployed identity, explicit SDK credential, identity endpoint access
Ingestion rejectedRole scope, current principal, role propagation, outbound connectivity
Requests without related signalsInstrumentation, filtering, sampling, operation IDs
Exporter warningsSDK diagnostics in runtime logs

Your own query access doesn't prove the app can ingest. For the sample, compare /api/diagnostics counters; an expired demo returns 410 and exhausted allowances 429. Don't enable local authentication to hide an identity failure, and don't send tokens or customer payloads to support.

Application Insights and the workspace have their own charges and retention; daily caps can overshoot and aren't hard spending limits, and sampling reduces ingestion.

6. Clean up resources​

Inspect the dedicated group and role assignment before deleting anything:

az resource list --subscription "$SUBSCRIPTION" --resource-group "$RG" \
--query "[].{name:name,type:type,id:id}" --output table
az role assignment list --subscription "$SUBSCRIPTION" --scope "$APPINSIGHTS_ID" \
--query "[?principalId=='$APP_PRINCIPAL_ID' && roleDefinitionName=='Monitoring Metrics Publisher'].{id:id,principalId:principalId,scope:scope}"

Confirm both belong to this exercise. Copy the assignment's id, delete it while its scope still exists, then delete the app:

PUBLISHER_ASSIGNMENT_ID="<exact-assignment-id-from-the-list>"
az role assignment delete --ids "$PUBLISHER_ASSIGNMENT_ID"
builder app delete --name "$APP" --subscription "$SUBSCRIPTION" --resource-group "$RG"

Delete the dedicated monitoring resources:

az resource delete --ids "$APPINSIGHTS_ID" --api-version 2020-02-02
az resource delete --ids "$WORKSPACE_ID" --api-version 2023-09-01

Refresh the inventory:

az resource list --subscription "$SUBSCRIPTION" --resource-group "$RG" \
--query "[].{name:name,type:type,id:id}" --output table

If Azure created a Smart Detection action group, delete it only after confirming this exercise owns it:

ACTION_GROUP_ID="<verified-exercise-owned-action-group-resource-id>"
az resource show --ids "$ACTION_GROUP_ID" --api-version 2023-01-01 \
--query "{id:id,name:name,type:type,location:location,groupShortName:properties.groupShortName,enabled:properties.enabled}"
az resource delete --ids "$ACTION_GROUP_ID" --api-version 2023-01-01

Delete the group only if it is empty:

REMAINING_COUNT=$(az resource list --subscription "$SUBSCRIPTION" \
--resource-group "$RG" --query "length(@)" --output tsv) &&
if [ "$REMAINING_COUNT" = "0" ]; then
az group delete --subscription "$SUBSCRIPTION" --name "$RG"
else
printf '%s\n' "Stop: the group still contains resources. Inspect them before continuing." >&2
false
fi

Never delete a shared workspace or another application's roles.