Log code app errors to Application Insights

Log code app errors to Application Insights

In my series on automated CI/CD for a Power Apps code app, the errors from the app become issues that an AI code agent fixes. This guide sets up the first step, where the app sends its errors to Application Insights.

The series has two alternatives for this step: Application Insights in this guide, or a Dataverse table. The overview of the series shows both.

What it does:

  1. The app catches the error. The Application Insights SDK picks up the uncaught errors and the unhandled promises, and a small function called logIfFailed picks up the failed calls.
  2. The app sends the error to an address in Azure. The environment has to allow that address first.
  3. Application Insights stores the error. You find it in the Azure portal a few minutes later.

You need an Azure subscription where you can create resources and a code app that reads from Dataverse through a generated service (in my app Dept_deptcasesService). The app is already published to your environment with the Power Apps CLI (pa), as in Microsoft’s quickstart. Step 8 needs an administrator of the environment.

Step 1. Create the Application Insights resource

The resource gives you the connection string the app sends the errors to. Sign in with az login, then run these commands in a terminal. Microsoft says the az monitor app-insights commands need the extension in the first line:

az extension add --name application-insights
az group create --name rec-dept-codeapp-rg --location norwayeast --output table
az monitor log-analytics workspace create --resource-group rec-dept-codeapp-rg --workspace-name rec-dept-codeapp-log --location norwayeast --query provisioningState --output tsv
az monitor app-insights component create --app rec-dept-codeapp-appi --resource-group rec-dept-codeapp-rg --location norwayeast --workspace rec-dept-codeapp-log --query connectionString --output tsv

Application Insights stores its data in a Log Analytics workspace, so the second command creates one in the same resource group and the third command points to it with --workspace. Without --workspace Azure creates a workspace for you in a resource group of its own.

Or create the resource in the Azure portal:

  1. Search for Application Insights in the Azure portal and select Create.
  2. Choose your subscription and a resource group. Create new under the field makes a new resource group.
  3. Enter a name and choose the region.
  4. Under Workspace details, choose a Log Analytics workspace. The portal suggests a new default workspace.
  5. Select Review + create and then Create. The portal answers “Your deployment is complete”.
  6. Select Go to resource.

The last az command prints the connection string. In the Azure portal it is on the Overview page of the resource under Connection string.

Step 2. Save the connection string

The app reads the connection string from a file as you build it, so the string stays out of your repo. Create a file called .env.local in the project folder:

VITE_APPINSIGHTS_CONNECTION_STRING=<your-connection-string>

The .gitignore of the Vite template leaves out every file that ends in .local. Microsoft says the connection string is visible in plain text in the browser of everyone who opens the app, and that it is no security key.

Step 3. Install the SDK

The app sends the errors with the Application Insights SDK. Run this in the project folder:

npm install @microsoft/applicationinsights-web

Step 4. Create errorLog.ts

src/errorLog.ts is the only new file, and it has everything the app needs to send errors. Create it with this content:

import { ApplicationInsights } from '@microsoft/applicationinsights-web'
import { setConfig } from '@microsoft/power-apps/app'
import type { IOperationResult } from '@microsoft/power-apps/data'

// Uncaught errors are collected by default. Rejected promises are not, so that is switched on.
const appInsights = new ApplicationInsights({
  config: {
    connectionString: import.meta.env.VITE_APPINSIGHTS_CONNECTION_STRING,
    enableUnhandledPromiseRejectionTracking: true,
  },
})
appInsights.loadAppInsights()

// The platform's own metrics: app start and every network request with its status code.
setConfig({
  logger: {
    logMetric: (metric) => appInsights.trackEvent({ name: metric.type }, metric.data),
  },
})

// A failed Dataverse or connector call does not throw. It returns success: false,
// so the app has to send that error on itself.
export function logIfFailed<T>(result: IOperationResult<T>, operation: string) {
  if (!result.success) {
    const error = result.error as { message?: string; status?: number; requestId?: string } | undefined
    appInsights.trackException(
      { exception: new Error(readMessage(error?.message) ?? `${operation} failed`) },
      { operation, status: error?.status, requestId: error?.requestId },
    )
  }
  return result
}

// Dataverse sends its error as JSON text. The readable sentence is in error.message.
function readMessage(message?: string) {
  try {
    return JSON.parse(message ?? '').error.message as string
  } catch {
    return message
  }
}

The file starts the SDK with the connection string from step 2. The SDK collects the uncaught errors by default, and enableUnhandledPromiseRejectionTracking adds the unhandled promises.

setConfig hands the platform’s own metrics to Application Insights: the app start and every network request with its status. Microsoft’s guide for Application Insights in code apps has the same setup.

logIfFailed takes the result of a call and a name for the operation. A failed result goes to Application Insights as an exception, together with the operation, the HTTP status and the request ID. The function returns the result unchanged, so the code around the call stays as it is.

Dataverse sends its error as a JSON text of several hundred characters. readMessage picks the readable sentence out of it.

Step 5. Load errorLog.ts as the app starts

The SDK has to start before the app does, so that it also catches an error from the first screen. Open src/main.tsx and add the import above the import of App:

import { StrictMode } from 'react'
import { createRoot } from 'react-dom/client'
import './errorLog.ts'
import './index.css'
import App from './App.tsx'

createRoot(document.getElementById('root')!).render(
  <StrictMode>
    <App />
  </StrictMode>,
)

Step 6. Wrap the Dataverse calls

A failed Dataverse call reaches Application Insights only through logIfFailed, so wrap every call to a generated service. Open src/App.tsx and import the function:

import { logIfFailed } from './errorLog.ts'

Put logIfFailed around each call. My app has a call that loads the cases and a call that creates a case:

async function load() {
  setState('loading')
  const result = logIfFailed(await Dept_deptcasesService.getAll(), 'load cases')
  if (result.success && result.data) {
    setCases(result.data)
    setState('ready')
  } else {
    setError(result.error?.message ?? 'Dataverse returned no data.')
    setState('error')
  }
}
async function addCase() {
  if (!title.trim()) return
  const result = logIfFailed(
    await Dept_deptcasesService.create({ dept_name: title.trim(), statecode: 0 }),
    'create case',
  )
  if (result.success) {
    setTitle('')
    await load()
  } else {
    setError(result.error?.message ?? 'Create failed.')
    setState('error')
  }
}

The second argument is a name you choose for the operation. The published code is minified (in my stored errors logIfFailed was called Py), so this name is how you see which call failed.

Step 7. Build and publish

Run these commands in the project folder:

npm run build
npx pa app push
  • npm run build checks the TypeScript code and builds the app into the dist folder. The connection string from .env.local goes into the built JavaScript in this command.
  • npx pa app push uploads the dist folder to your environment as a new version of the code app. pa is the Power Apps CLI from the npm package @microsoft/power-apps-cli, and it reads the environment and the app from power.config.json.

Step 8. Allow the address in the environment

The published app sends nothing to Application Insights until the environment allows the address. Every code app in an environment has a list of the addresses it may contact, and Microsoft’s documentation says the list is empty by default. Add the ingestion address from your connection string (the value after IngestionEndpoint=) to that list. The list is the connect-src setting in the Content Security Policy (CSP) of the environment.

  1. Open the Power Platform admin center and select Manage > Environments. Select your environment and then Settings.
  2. Expand Product and select Privacy + Security.
  3. Under Content security policy, select the App (code) tab.
  4. Under Configure directives, turn off Use default connect-src.
  5. Select Add and enter the ingestion address, in my case https://norwayeast-0.in.applicationinsights.azure.com. Leave the sources that are already in the list.
  6. Select Save.

Microsoft says you must be an administrator of the environment to change the setting, and that it applies to every code app in the environment. In my tenant the change took between 2 and 7 minutes to reach the app, and I had to reload the page. I added the ingestion address and no other address.

With npx pa app run (Local Play) the errors arrived without this change.

Step 9. Check that it works

Add a temporary button that throws an error. Put it under the form in src/App.tsx:

<button
  onClick={() => {
    throw new Error('Test: error in a click handler')
  }}
>
  Throw error
</button>
  1. Run npm run build and npx pa app push. Open the app and select Throw error.
  2. Open the Application Insights resource in the Azure portal and select Investigate > Search. Select See all data in the last 24 hours and set View as to Individual items. Check that the list has a row marked EXCEPTION with the text “Uncaught Error: Test: error in a click handler”. My rows were there 1 to 4 minutes after the click.
  3. Remove the button. Build and publish again.

What a stored error contains

  • The message and a Problem Id, which is the message followed by ” at ” and the name of the function.
  • For a failed call: the operation, the HTTP status and the request ID as custom dimensions.
  • The stack as the browser saw it. In the published app that is the minified file, for example assets/index-<hash>.js:17:107370.
  • An anonymous user ID. It changed between page loads in my runs.
  • The platform’s metrics as CUSTOM EVENT rows: sessionLoadSummary, networkRequest and dataRequestsSummary.

Microsoft says Application Insights only captures telemetry after the app has loaded. An app that fails to start does not show up there, only in Monitor in the Power Platform admin center.

This guide sets up the basics. For a production app you can also upload source maps to Application Insights, so the stack shows your own code instead of the minified code.

Posts in the series

Log the errors

Documentation and code


Posted

in

, ,

by

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *