By default when you configure Application Insights, the Instrumentation key is hardcoded in the JavaScript snippet
and the ApplicationInsights.config:
This makes it very hard to integrate your application into your devops pipeline and use different instrumentation keys for different environments(development, test, production).
Let’s see how we can fix this:
- Start by commenting out the InstrumentationKey setting in the ApplicationInsights.config:
- Instead add an extra appsetting to your web. config. By using the web.config you can use the web.config transformations to inject different instrumentation keys for different environments.
- Now we have to tell Application Insights to use the key specified in our web.config. Therefore add the following line of code to the Application_Start method of the global.asax:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
protected void Application_Start() | |
{ | |
TelemetryConfiguration.Active.InstrumentationKey = WebConfigurationManager.AppSettings["InstrumentationKey"]; | |
RegisterRoutes(RouteTable.Routes); | |
AreaRegistration.RegisterAllAreas(); | |
} |
- As a last step we also have to fix this for the JavaScript snippet injected into our page:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<script type="text/javascript"> | |
var appInsights = window.appInsights || function (a) { | |
function b(a) { c[a] = function () { var b = arguments; c.queue.push(function () { c[a].apply(c, b) }) } } var c = { config: a }, d = document, e = window; setTimeout(function () { var b = d.createElement("script"); b.src = a.url || "https://az416426.vo.msecnd.net/scripts/a/ai.0.js", d.getElementsByTagName("script")[0].parentNode.appendChild(b) }); try { c.cookie = d.cookie } catch (a) { } c.queue = []; for (var f = ["Event", "Exception", "Metric", "PageView", "Trace", "Dependency"]; f.length;)b("track" + f.pop()); if (b("setAuthenticatedUserContext"), b("clearAuthenticatedUserContext"), b("startTrackEvent"), b("stopTrackEvent"), b("startTrackPage"), b("stopTrackPage"), b("flush"), !a.disableExceptionTracking) { f = "onerror", b("_" + f); var g = e[f]; e[f] = function (a, b, d, e, h) { var i = g && g(a, b, d, e, h); return !0 !== i && c["_" + f](a, b, d, e, h), i } } return c | |
}({ | |
instrumentationKey:"@Microsoft.ApplicationInsights.Extensibility.TelemetryConfiguration.Active.InstrumentationKey" | |
}); | |
window.appInsights = appInsights, appInsights.queue && 0 === appInsights.queue.length && appInsights.trackPageView(); | |
</script> |