Skip ILogger or ILoggerFactory for constructors in AspNet Core?

The MS docs article , An Introduction to Logging in ASP.NET Core, provides 2 examples of constructor implementation

  • using iLogger

    private readonly ILogger _logger; public TodoController(ILogger<TodoController> logger) { _logger = logger; } 
  • and ILoggerFactory

     private readonly ILogger _logger; public TodoController( ILoggerFactory loggerFactory) { _logger = loggerFactory.CreateLogger<TodoController>(); } 

My question is that I have to go to child classes called from my controller

  • pass ILoggerFactory my child classes called from the controller and in every call to the LoggerFactoryExtensions.CreateLogger<MyChildClass>() or

  • pass the parent ILogger<MyController> controller for each child class created from the controller and having a non-common ILogger parameter.

In magazines, I prefer to see a separate “MyChildClass” category for each class, and not all classes use the “MyController” category from the parent controller.
However, CreateLogger in each object construct can be an expensive operation (e.g. see https://github.com/aspnet/Logging/issues/524 )

Which option would you recommend? Can you suggest any other approach?

+20
c # dependency-injection logging asp.net-core .net-core
source share
1 answer

This is more of a design problem.

In any case, the controller should not create child classes. This is not a problem that the dispatcher must deal with SRP (single responsibility principle).

My question is what should I pass to child classes called from my controller

If you prefer to separate registrars, then there really is no other choice but to have child (dependent) classes with their own registrars.

Ask the lesson children to enter their own logger.

 public class TodoRepository : ITodoRepository { private readonly ILogger logger; public TodoRepository(ILogger<TodoRepository> logger) { this.logger = logger; } //... } 

and then enter the child class in the controller.

 public class TodoController : Controller { private readonly ILogger logger; private readonly ITodoRepository todoRepository; public TodoController(ILogger<TodoController> logger, ITodoRepository todoRepository) { this.logger = logger; this.todoRepository = todoRepository; } //... } 

Thus, child registrars will be eliminated when child classes are enabled and entered into the controller.

+12
source share

All Articles