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:
services.Configure<TelemetryConfiguration>((config) =>
{
config.TelemetryInitializers.Add(new CustomInitializer("my app", Guid.NewGuid().ToString()));
});
This didn't work.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With