Search code examples
azure-application-insights

What is the easiest way to add custom dimensions to default Request Telemetry for App service?


I just leverage default Application Insights logging to log the request telemetry without ANY custom code. The request telemetry looks like this:

timestamp [UTC]     2019-12-19T00:22:10.2563938Z
id                  |a758472d124b6e4688a33b2ad9755f33.b3979544_
name                GET MyMethod [type]
url                 https://xxxx
success             True
resultCode          200
duration            153.2676
performanceBucket   <250ms
itemType            request
customDimensions 
    AppId                           xxxx-xxxx-xxxx-xxxx-xxxxxx
    AspNetCoreEnvironment:          west us
   _MS.ProcessedByMetricExtractors (Name:'Requests', Ver:'1.1')

Now I want to add a new property to customDimensions in Request telemetry, say, correlationId. What is the easiest way to to it? I just want to expend the existing request telemetry, don't want to create new event.


Solution

  • For adding custom dimensions, you can take use of ITelemetryInitializer.

    Here is an example for a .NET core web project:

    1.Add a class named MyTelemetryInitializer to the project, and the code like below:

    public class MyTelemetryInitializer : ITelemetryInitializer
    {
        public void Initialize(ITelemetry telemetry)
        {
            var requestTelemetry = telemetry as RequestTelemetry;
    
            //if it's not a request, just return.
            if (requestTelemetry == null) return;
    
            if (!requestTelemetry.Properties.ContainsKey("correlationId"))
            {
                requestTelemetry.Properties.Add("correlationId", "id_123456");
            }
        }
    
     }
    

    2.In Startup.cs -> ConfigureServices method, use the following code:

        public void ConfigureServices(IServiceCollection services)
        {
           //your other code           
    
            //register the class MyTelemetryInitializer.
            services.AddSingleton<ITelemetryInitializer, MyTelemetryInitializer>();
        }
    

    The test result:

    enter image description here

    If you're using other programming language, please follow the official doc and use the proper method for ITelemetryInitializer.