ILoggerFactory connects logging providers with the ILogger instances used by application code. Register providers with the factory, then call CreateLogger() to create a logger that writes to every configured provider. section 26.1.2
Use ILoggerFactory when you need to control logger creation directly:
- Create a logger with an explicit category, such as "RecipeApp.RecipeService". section 26.2.2
- Create a category from a type with CreateLogger<RecipeService>(), equivalent to using ILogger<RecipeService>. section 26.2.2
- Prefer injecting ILogger<T> for ordinary application logging; use ILoggerFactory when customized categories or direct creation are useful. section 26.2.2
Creating a logger with a custom category
public class RecipeService { private readonly ILogger _log; public RecipeService(ILoggerFactory factory) { _log = factory.CreateLogger("RecipeApp.RecipeService"); } } section 26.2.2
Figure 26.3 The components of the ASP.NET Core logging framework. You register logging providers with an ILoggerFactory, which creates implementations of ILogger. You write logs to the ILogger, which delegates to the ILogger implementations that write logs to the console or a file. You can send logs to multiple locations with this design without having to configure the locations when you create a log message.
The provider diagram shows how one ILoggerFactory can create loggers that delegate each message to multiple destinations, such as the console or a file. section 26.1.2
