Search code examples
asp.net-core.net-coreazure-application-insights

How to set the cloud_roleName for Application Insights for .NET Core?


I am trying to set the cloud_RoleName property to disambiguate different components in a system tracked with Azure Application Insights.

How can I set the property for services running with ASP.NET Core?


Solution

  • RoleNames are by default populated. Is that not the case you observe or you want to override the behaviour? To override the rolename, the following should help:

    Write a TelemetryInitializer like the one below to populate RoleName to your desired value.

    public class MyRoleNameInitializer : ITelemetryInitializer  
     {
          public void Initialize(ITelemetry telemetry)
            {
               telemetry.Context.Cloud.RoleName = "MyCustomRoleName";
            }
     }
    

    Then add the following line to add the TelemetryInitializer to the configuration, in the ConfigureServices method of you application startup class.

        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc();
            services.AddSingleton<ITelemetryInitializer, MyRoleNameInitializer>();
        }
    

    Note: If you used AddApplicationInsightsTelemetry() in the ConfigureServices of your Startup class to add Application Insights, then the above line should be done before AddApplicationInsightsTelemetry() as shown below.

        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc();
            services.AddSingleton<ITelemetryInitializer, MyRoleNameInitializer>();
            services.AddApplicationInsightsTelemetry("ikey");
        }