5

I'm confused about the difference between using System.Diagnostics.Trace Trace.TraceInformation("This is a test") and using the ILogger logging abstraction logger.LogInformation("This is a test").

I'm working in a .Net Core 2.2 project and plan to deploy this as an Azure Web App. Is there a difference in the two approaches? Is one better suited for what I'm doing than the other? Why would one use one over the other?

RHarris
  • 10,641
  • 13
  • 59
  • 103
  • 1
    This [question](https://stackoverflow.com/questions/172372/tracing-versus-logging-and-how-does-log4net-fit-in) is 11 years old, but I think the top couple of answers is still applicable. –  Dec 30 '19 at 19:26
  • 2
    [Logging in .NET Core and ASP.NET Core](https://learn.microsoft.com/en-us/aspnet/core/fundamentals/logging/?view=aspnetcore-3.1). You basically want to log, and not use the diagnostics trace. If you *need* the diagnostics trace, there is also a `TraceSourceLoggerProvider` for logging. – As for when to do `LogInformation`, `LogTrace` etc., see the [docs on log levels](https://learn.microsoft.com/en-us/aspnet/core/fundamentals/logging/?view=aspnetcore-3.1#log-level). – poke Dec 31 '19 at 12:11

2 Answers2

1

Apparently, there is no demarcation which to use when. If you ask yourself "what is the intention?" and the answer happens to be "interacting with system processes, event logs, or performance counters" go for System.Diagnostics. If the answer happens to be "I just want application logging", then go for Logger.

For Azure Web App, you might want to use AddAzureWebAppDiagnostics.

Difference between Logging and Tracing?

The way I stay clear about it is Logging helps you with reporting out any errors.

But if you want to understand which part of a function is causing the error or any performance bottleneck, then use Tracing. Tracing helps to understand how the flow of control or program has been. You might also want to see other levels of logging like fatal, warning, debug, info, etc.

Shridhar R Kulkarni
  • 6,653
  • 3
  • 37
  • 57
  • I guess where I get confused is that Logging has a `Trace` level. So what is the difference between `logger.Log(LogLevel.Trace, "Here is a trace message")` and `Trace.TraceInformation("Here is a trace message")`? – RHarris Dec 30 '19 at 19:42
  • @RHarris: Updated the answer. – Shridhar R Kulkarni Dec 30 '19 at 20:06
1

The main difference is that ILogger is not part of the framework (netstandard or .NET 5+), it is a higher level logging/tracing framework. System.Diagnostics is part of the .NET framework, out of the box.

Other differences are that ILogger can be used with dependency injection.

Also, there is this

diegosasw
  • 13,734
  • 16
  • 95
  • 159
  • Besides the main differences, the key distinctions in logging APIs is as following 1. Structured logging 2. Configuration 3. Sinks – Jack Liu Shurui May 15 '23 at 08:43