0
votes

In this code example for creating a logging instance using Dependency Injection in ASP.NET Core why is the logger type the controller class when injecting the logger in the constructor?

ILogger<TodoController> logger

Instead of ILogger<TodoController> shouldn't it be just ILogger logger passed into the constructor?

Code example:

public class TodoController : Controller
{
    private readonly ITodoRepository _todoRepository;
    private readonly ILogger _logger;

    public TodoController(ITodoRepository todoRepository,
        ILogger<TodoController> logger)
    {
        _todoRepository = todoRepository;
        _logger = logger;
    }

Source: https://docs.microsoft.com/en-us/aspnet/core/fundamentals/logging/?tabs=aspnetcore2x&view=aspnetcore-2.2

1
@JohnB LOL not an error - Jonathan Kittell
I think it's ILogger<TCategoryName> and not ILogger<T>... docs.microsoft.com/en-us/dotnet/api/… - Jonathan Kittell
ah - thanks for the correction! - Jazb
You need to also add some code in your Startup.cs to configure the dependency injection. Your code sample only shows the portion of the code where you are retrieving the objects governed by dependency injection. - Glenn Ferrie

1 Answers

3
votes

Look at some of the sample code:

_logger.LogInformation(LoggingEvents.GetItem, "Getting item {ID}", id);

Then the corresponding sample output:

info: TodoApi.Controllers.TodoController[1002]
      Getting item 0

Notice that the name of the controller is included even though it wasn't specified in the call to LogInformation?

That's why. It lets the logger automatically include the class that logged the information.