microsoft / ApplicationInsights-dotnet-logging

.NET Logging adaptors
106 stars 49 forks source link

Direct Use of TelemetryClient in ASP.NET core best practices? #313

Closed yulshMSFT closed 5 years ago

yulshMSFT commented 5 years ago

Hi,

General-ish question about using app insights logging in ASP.NET core web APIs.

As far as I can tell, this library (simplifying here of course) wraps TelemetryClient in abstractions from aspnetcore. In the process, it makes it impossible to use the full API provided by TelemetryClient (like TrackDependency, for example) because everything is behind ILogger from aspnetcore.

So it seems like the only way to use these features is to use TelemetryClient directly, ie. inject it as a singleton into IServiceCollection. Another way might be to write a custom TelemetryProcessor to re-map specific log messages to Dependency Logs by some type of convention (not nice).

I'm leaning towards using TelemetryClient directly, but I wanted to understand what I would be missing out on by skipping all the logging abstractions from aspnetCore. Are there any performance gains/optimizations provided by logging through the abstractions provided by the framework?

Thanks, let me know if this is not the right forum for this type of question.

RamjotSingh commented 5 years ago

ILogger has a few advantages of it's own so for TraceLogging I would recommend using ILogger while for Metric\Event Logging you can directly use TelemetryClient.

ILogger provides additional information through Context like the connection details and allows you to define and control scopes using BeginScope.

For shared code ILogger allows you to just take dependency on .NET platform instead of a SDK like AI etc.

There is no clear answer and you can choose to use TelemetryClient or ILogger. Since eventually everything goes through TelemetryClient regardless, perf should not be a differentiator.

However if you choose to not setup ILogger at all you will not be able to get any traces from .NET core platform, things like low level exceptions, return code traces etc.

pharring commented 5 years ago

One quick point to add: If you're already using the ILogger implementation, there should be no need to inject your own TelemetryClient. Use IOptions<TelemetryConfiguration> and create a TelemetryClient from that. See https://docs.microsoft.com/en-us/azure/azure-monitor/app/ilogger#im-using-the-standalone-package-microsoftextensionsloggingapplicationinsights-and-i-want-to-log-some-additional-custom-telemetry-manually-how-should-i-do-that

yulshMSFT commented 5 years ago

Thanks all! really appreciate the prompt and clear responses, particularly like not re-injecting a TelemetryClient !