首页 > 解决方案 > netcore 2.1:无法使用 new LoggerFactory() 创建记录器

问题描述

我正在将 netcore 2.0 项目升级到 netcore2.1

我有一个创建记录器的基本测试控制器,如下所示:

public class WSTestController
{
    protected readonly ILogger _log;
    protected readonly HttpClient _client;
    protected readonly IServiceCollection _services;

    public WSTestController() {
        _log = new LoggerFactory().AddConsole().CreateLogger(this.GetType().Name);
        var testContext = new TestContext();
        _client = testContext.Client;
    }

这适用于 netcore 2.0,但在 netcore 2.1 中我收到以下错误:

controllers/WSTestController.cs(22,40): error CS1061: 
'LoggerFactory' does not contain a definition for 'AddConsole' and no accessible extension method 'AddConsole' accepting a first argument of type 'LoggerFactory' could be found 
(are you missing a using directive or an assembly reference?) [[...]/src/mtss-ws.integrationtests/mtss-ws.integrationtests.csproj]

如何在 netvore 2.1 中手动实例化控制台记录器(即没有 DI)?

标签: logging.net-core

解决方案


它应该在 netcore2.1 中仍然可以工作,看看这里

您也可以通过简单地使用 AddProvider 方法手动执行此操作:

loggerFactory.AddProvider(
    new ConsoleLoggerProvider(
        (text, logLevel) => logLevel >= LogLevel.Debug, true));

推荐阅读