Logging with ILogger
The ILogger
class is part of the Microsoft.Extensions.Logging.Abstractions
NuGet package. If you work on an ASP.NET Core application, worker service, or use other Microsoft.Extensions
packages, you already depend on it transitively.
The ILogger
interface exposes a few methods:
Log
records a log message with a given level, ID, exception, state, and formatter. The state type is generic but should contain a message, along with all the parameters and their names.IsEnabled
checks whether logging at this level is enabled.BeginScope
adds an object to the logging scope, allowing you to enrich nested log records with it. We saw scopes in action in Chapter 2, Native Monitoring in .NET, where we annotated console logs with trace context and ASP.NET Core request information.
It’s common to use convenient extension methods defined in the Microsoft.Extensions.Logging.LoggerExtensions
class instead of the vanilla ILogger.Log
method.
Before...