C#HostBuilder日志记录配置。非通用记录器为null

时间:2019-11-21 12:53:43

标签: c# logging .net-core

我有一个dotnet core 3.0控制台应用程序,其中安装了以下软件包:

<PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="3.0.1" />
<PackageReference Include="Microsoft.Extensions.Hosting" Version="3.0.1" />
<PackageReference Include="Microsoft.Extensions.Logging.Console" Version="3.0.1" />

这是我的全部最小的,可复制的完整程序:

using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;

namespace logging
{
    class Program
    {
        static void Main(string[] args)
        {
            var host = new HostBuilder()
                .ConfigureLogging((context, b) =>
                {
                    b.AddConsole();
                })
                .Build();

            var logger = host.Services.GetService<ILogger>();
            var genericLogger = host.Services.GetService<ILogger<Program>>();
        }
    }
}

当我尝试解析两个记录器时,通用记录器可以解决,但非通用记录器始终为null。谁能找到为什么我的非通用记录器为null的原因?

1 个答案:

答案 0 :(得分:1)

这是因为没有专门将ILogger添加到服务集合中。只有通用

/// <summary>
/// Adds logging services to the specified <see cref="IServiceCollection" />.
/// </summary>
/// <param name="services">The <see cref="IServiceCollection" /> to add services to.</param>
/// <param name="configure">The <see cref="ILoggingBuilder"/> configuration delegate.</param>
/// <returns>The <see cref="IServiceCollection"/> so that additional calls can be chained.</returns>
public static IServiceCollection AddLogging(this IServiceCollection services, Action<ILoggingBuilder> configure)
{
    if (services == null)
    {
        throw new ArgumentNullException(nameof(services));
    }

    services.AddOptions();

    services.TryAdd(ServiceDescriptor.Singleton<ILoggerFactory, LoggerFactory>());
    services.TryAdd(ServiceDescriptor.Singleton(typeof(ILogger<>), typeof(Logger<>)));

    services.TryAddEnumerable(ServiceDescriptor.Singleton<IConfigureOptions<LoggerFilterOptions>>(
        new DefaultLoggerLevelConfigureOptions(LogLevel.Information)));

    configure(new LoggingBuilder(services));
    return services;
}

Source

为了证明这一点,如果要使用您的示例调用以下内容

var logger = host.Services.GetRequiredService<ILogger>();

它将引发一个异常,即无法解析请求的类型。

ILogger通常不用于显式注入或解析,而是作为分配的基本类型

例如

public class AboutModel : PageModel {
    private readonly ILogger logger;

    public AboutModel(ILogger<AboutModel> logger) {
        this.logger = logger;
    }

    //...
}

或者在非主机控制台应用程序中

var loggerFactory = LoggerFactory.Create(builder => {
    builder.AddConsole();
});

ILogger logger = loggerFactory.CreateLogger<Program>();

引用Logging in .NET Core and ASP.NET Core