microsoft / ApplicationInsights-dotnet-logging

.NET Logging adaptors
106 stars 49 forks source link

.net core DI - how to get TelemetryClient #278

Closed MikeAtETI closed 5 years ago

MikeAtETI commented 5 years ago

I configure a ServiceProvider, add AI logging through:

sc.AddLogging( builder => { builder.AddApplicationInsights("XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXX"); builder.AddFilter("", LogLevel.Trace); });

If I try and do ServiceProvider.GetRequiredService it always throws an exception.

cijothomas commented 5 years ago

@MikeAtETI Please completely describe what you are trying to do and how. The post seems imcomplete?

MikeAtETI commented 5 years ago

I'm trying to track an event (or a pageview) to the same Application Insights as the main ILogger bits are going to. I could be missing something as I'm new at this, but it looks like the TelemetryClient is what I need but it would need all the telemetryinitializers etc re-hooking to it?

cijothomas commented 5 years ago

@MikeAtETI please check if the docs help you to get started : https://docs.microsoft.com/en-us/azure/azure-monitor/app/ilogger

By installing just Microsoft.Extensions.Logging.ApplicationInsights, you'll not get TelemetryClient from DI. its injected only if using Microsoft.ApplicationInsights.AspNetCore.

pharring commented 5 years ago

I bumped into this too, but after a bit of digging, I was happy when I figured out that, with just the ILogger's AddApplicationInsights() extension method, I could inject IOptions<TelemetryConfiguration> into my controllers:

i.e.

using Microsoft.ApplicationInsights;
using Microsoft.ApplicationInsights.Extensibility;
using Microsoft.Extensions.Options;
// etc.

public class MyController : ApiController
{
   private readonly TelemetryClient _telemetryClient;
   private readonly ILogger _logger;

   public MyController(IOptions<TelemetryConfiguration> options, ILogger<MyController> logger)
   {
        _telemetryClient = new TelemetryClient(options.Value);
        _logger = logger;
   }

  // etc.
}
cijothomas commented 5 years ago

@pharring Thanks! I was updating the docs with information on how to get TC used by ilogger.

MikeAtETI commented 5 years ago

@pharring @cijothomas thanks - that does exactly what I need

cijothomas commented 5 years ago

https://docs.microsoft.com/en-us/azure/azure-monitor/app/ilogger#frequently-asked-questions FAW updated to included this .