microsoft / ApplicationInsights-dotnet-logging

.NET Logging adaptors
106 stars 49 forks source link

Use custom TelemetryClient #279

Closed Alin764 closed 5 years ago

Alin764 commented 5 years ago

I’m using Application Insights in a WebJob with a triggered function. I need to use a custom TelemetryClient to set Session ID

My previous code was registering TelemetryClient like this

services.Add(
    new ServiceDescriptor(typeof(TelemetryClient), 
    provider => provider.GetService<ITelemetryClientFactory>().Create(appInsightsKey, functionName), 
    ServiceLifetime.Scoped));

services.AddScoped<ILoggerFactory, LoggerFactory>(serviceProvider=>
{
    var loggerFactory = new LoggerFactory();
    loggerFactory.AddApplicationInsights(serviceProvider);
    return loggerFactory;
});

How to make Application insights when added with loggingBuilder to use my custom Telemetry Client

cijothomas commented 5 years ago

can you describe the issue a bit more clearer - how was your code before, and how is it now, and what is the difference in observed behavior.

Alin764 commented 5 years ago

@cijothomas In fact I want to use my custom TelemetryClient as it was working in my previous code:

Previous code:

services.AddScoped<ILoggerFactory, LoggerFactory>(serviceProvider=>
{
    var loggerFactory = new LoggerFactory();
    loggerFactory.AddApplicationInsights(serviceProvider); // this is deprecated now
    return loggerFactory;
});

New recommended way to add Application Insights logger

services.AddLogging(loggingBuilder => {
        loggingBuilder.AddFilter<ApplicationInsightsLoggerProvider>("", LogLevel.Trace);
            loggingBuilder.AddApplicationInsights("--YourAIKeyHere--");         
            }); 
RamjotSingh commented 5 years ago

ILogger extensions for Application insights uses it's own TelemetryClient. You can use ITelemetryInitializer or ITelemeryProcessor to set additional metadata on outgoing telemetry items.

cijothomas commented 5 years ago

https://github.com/Microsoft/ApplicationInsights-dotnet-logging/issues/278#issuecomment-482296406 Check this comment if you are looking to create own TelemetryClient with same config used by ILogger.

cijothomas commented 5 years ago

FAQ updated to include explanation on how to get a TC when using ilogger. https://docs.microsoft.com/en-us/azure/azure-monitor/app/ilogger#frequently-asked-questions