Ali
Ali

Reputation: 73

Change Instrumentation key for logging in ASP.NET Core using Application Insights

Is there any way to switch instrumentation key on the run, based on some business logic to target log destination to different Application Insights instances.

As we configure Application Insights to be used as Logger in startup project, so I can't find any out of the box approach or hack to a workaround for this requirement.

The above switching can be easily done if I am using Application insight as a telemetry client because in this case, I can provide different instrumentation keys on the run to the client which is not the same for ILogger getting injected using built-in DI of ASP.NET Core.

Upvotes: 1

Views: 2382

Answers (2)

cijothomas
cijothomas

Reputation: 3196

Write an initializer to conditionally override instrumentation key like below:

class MyTelemetryInstrumentationKeyOverrider : ITelemetryInitializer
    {
        public void Initialize(ITelemetry telemetry)
        {
            // conditionally do this.
            telemetry.Context.InstrumentationKey = "newkey";
        }
    }

Upvotes: 3

Sajeetharan
Sajeetharan

Reputation: 222712

This has to be done at the point where the application is started, in that case YES. but there is no way to change after application is started.

You can have a look at Dynamic instrumentation key

protected void Application_Start()
{
  Microsoft.ApplicationInsights.Extensibility.
    TelemetryConfiguration.Active.InstrumentationKey = 
      // - for example -
      WebConfigurationManager.AppSettings["ikey"];

Upvotes: 2

Related Questions