Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Application Insights: Adding cloud role name via custom ITelemetryInitializer in .net core 3.1 console app does not pick up the cloud role name

I'm using HostBuilder to configure the console app in Program.cs.

In ConfigureServices:

services.AddSingleton<ITelemetryInitializer, CustomInitializer>(p => new CustomInitializer("my app", Guid.NewGuid().ToString()));

services.AddApplicationInsightsTelemetryWorkerService();

in ConfigureLogging:

logging.ClearProviders();
logging.AddConfiguration(hostingContext.Configuration.GetSection("Logging"));
logging.AddNLog(NLog.LogManager.LoadConfiguration("nlog.config").Configuration);
logging.AddApplicationInsights();

in CustomInitializer.cs:

class CustomInitializer : ITelemetryInitializer
{
    private readonly string _roleName;
    private readonly string _roleInstance;

    public CloudRoleNameInitializer(string name, string instance)
    {
        _roleName = name;
        _roleInstance = instance;
    }

    public void Initialize(ITelemetry telemetry)
    {
        telemetry.Context.Cloud.RoleName = _roleName;
        telemetry.Context.Cloud.RoleInstance = _roleInstance;
    }
}

As you can see I am using nlog as well. When I log my messages I can see that the cloud role name isn't set to "my app" instead is set to my computer name. I experimented with a few possibilities in the ConfigureServices section:

Trial 1:

services.Configure<TelemetryConfiguration>((config) =>
        {
            config.TelemetryInitializers.Add(new CustomInitializer("my app", Guid.NewGuid().ToString()));
        });

This didn't work.

Trial 2

TelemetryConfiguration.Active.TelemetryInitializers.Add(new CustomInitializer("my app", Guid.NewGuid().ToString()));

This worked very well but I kept getting the IDE warning that this was now obsolete in .net core

I've checked all the documentation there is nothing which gives me a good idea on a substitute for using TelemetryConfiguration.Active. It seems most examples are geared toward .net core web apps and not console.

like image 981
Suemayah Eldursi Avatar asked Jan 20 '26 09:01

Suemayah Eldursi


1 Answers

NLog seems like using the TelemetryConfiguration.Active for creation of the TelemetryClient so all ITelemetryInitializer are getting ignored.

My solution for this was to add following setting for application insights

"ApplicationInsights": {
    "ConnectionString": "xxx",
    "EnableActiveTelemetryConfigurationSetup": true 
},

It seems that EnableActiveTelemetryConfigurationSetup == true automatically propagates telemetry settings from ServiceCollection into TelemetryConfiguration.Active.

like image 111
Arman Avatar answered Jan 23 '26 21:01

Arman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!