NuGet Packages
The ILogger
and ILoggerFactory
interfaces are located in Microsoft.Extensions.Logging.Abstractions
, with their default implementation found in Microsoft.Extensions.Logging
.
Log Category
There are two ways to specify the category: one is using class objects, and the other is to create them manually. Once you create an ILogger
object, a "category" will be assigned to it. This category is included in every log message created by this ILogger
instance. The category can be any string, but it is convention to use the class name, such as "TodoApi.Controllers.TodoController". You can obtain an ILogger
instance using ILogger<T>
, which uses the fully qualified type name of T
as the category:
public class TodoController : Controller
{
private readonly ITodoRepository _todoRepository;
private readonly ILogger _logger;
public TodoController(ITodoRepository todoRepository,
ILogger<TodoController> logger)
{
_todoRepository = todoRepository;
_logger = logger;
}
}
To explicitly specify the category, you can call ILoggerFactory.CreateLogger
:
public class TodoController : Controller
{
private readonly ITodoRepository _todoRepository;
private readonly ILogger _logger;
public TodoController(ITodoRepository todoRepository,
ILoggerFactory logger)
{
_todoRepository = todoRepository;
_logger = logger.CreateLogger("TodoApiSample.Controllers.TodoController");
}
}
文章评论