ASP.NET Core Logging

2019年7月30日 106点热度 1人点赞 1条评论
内容目录

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&lt;TodoController&gt; 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(&quot;TodoApiSample.Controllers.TodoController&quot;);
    }
}

痴者工良

高级程序员劝退师

文章评论