Adding Application Insights to multiple WebApps

I’m working on a project that uses Angularjs on the front-end and uses a lot of REST services that are hosted in Azure on WebApps. We have split the domains of the project properly and detached all the external systems, this leaves me with about 15 WebApps. All these WebApps created an Application Insights account in the portal and it was time to hook them up. What I didn’t want is have 15 Application Insights accounts to look after and setup alerts for, after all it’s just one app.

So I went on and setup one new common AI account for the app and deleted the auto created ones. But I also didn’t want my dev and test environments to mix with my production environment, therefore I created an Application Insight account per environment and configuration. The link between the app and the application insights account is made by the InstrumentationKey in the ApplicationInsights.config. What I needed was that the InstrumentationKey is in my web.config because then I would be able to use my publish transforms.

How to use the instrumentation key from the web.config

First zero out the InstrumentationKey guid in the ApplicationInsights.config file. Next add an appsetting in the web.config named InstrumentationKey or something else that makes sense. Now we need to add some code, the code needs the run as early as possible and in my case that is in the Application_Start method in the Global.asax file. Add the following line of code:

Microsoft.ApplicationInsights.Extensibility.TelemetryConfiguration.Active.InstrumentationKey =
System.Web.Configuration.WebConfigurationManager.AppSettings["InstrumentationKey"];

This sets the instrumentationkey of the active configuration to your appsetting. All you need to do now is set the appsetting transforms for the different configurations:

  <add key="InstrumentationKey" value="blablabl-abla-blab-labl-ablablablabl" xdt:Transform="Replace" xdt:Locator="Match(key)"/>

That’s all I guess. I’ve got a shiny dashboard with some cool stuff.

But wait!

I see some exceptions but when I click on them to find out what’s going on it says: “Learn how to track exceptions for failed requests” and gives an example of a try-catch block there. I’m not doing that for every method in all of my controllers!

Before I started typing away I bingled and found the next example: AiExceptionLogger.cs. You can put this in your project and in the Register method in the WebApiConfig.cs you can hook this in like this:

config.Services.Add(typeof(IExceptionLogger), new AiExceptionLogger());

And there you are, exception tracking in Application Insights.

Advertisements