liveBook · Manning

ILoggerFactory

As explained in ASP.NET Core in Action, 3e

ILoggerFactory is a .NET logging abstraction that registers logging providers and creates loggers associated with those providers.

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.
CH26_F03_Lock3

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

How ASP.NET Core in Action, 3e covers it

How deep it goes
Explains provider wrapping, category selection, and logger creation, but recommends ILogger<T> for routine use.
Examples
Uses console-provider configuration, a RecipeService custom category, and generic CreateLogger<RecipeService>().
What it assumes
Assumes familiarity with ASP.NET Core dependency injection and ILogger, while establishing provider registration and category creation.
What you can do after
Operate/configure ASP.NET Core logging by registering providers and creating categorized loggers through ILoggerFactory.
How it connects
Connects ILoggerFactory with ILoggerProvider, ILogger, dependency injection, log categories, and logging configuration.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of ASP.NET Core in Action, 3e. The section links point to the parts of the book it draws on.