netcore 2.0 在 DI 容器中创建日志记录时不记录跟踪和调试

netcore 2.0 not logging trace and debug when logging created in DI container

我有一个控制台应用程序,它将使用 DI 提供配置(选项模式)、日志记录和应用程序内对服务的其他服务引用。

我有一个问题,日志记录正在为 Info/Warning/Error/Critical 工作,但是 DebugTrace 没有出现。我已将控制台级别设置为 Trace。如果我只是创建一个记录器工厂,则会显示所有日志。

听起来像是在使用默认设置。对于在 DI 服务集合中创建的记录器,是否有其他方法来配置日志级别?

我已尝试在 post、编辑 2 link 中提到的服务集合上添加处置,但没有成功。

using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Console;
using System;

namespace DownloadClientData.App
{
    class Program
    {
        static int Main(string[] args)
        {
            //***if I use this way to create the logger in the DI container, debug and trace messages are not displayed
            var serviceCollection = new ServiceCollection();
            serviceCollection.AddLogging();

            //tried this alternative too - no change...
            //serviceCollection.AddLogging(LoggingBuilder => LoggingBuilder.AddFilter<ConsoleLoggerProvider>("All Categories", LogLevel.Trace));
            var serviceProvider = serviceCollection.BuildServiceProvider();
            var loggerFactory = serviceProvider.GetService<ILoggerFactory>();

            //***If I comment out the above lines and uncomment the below line, all 6 logs are displayed.

            //var loggerFactory = new LoggerFactory();
            loggerFactory
                .AddConsole(LogLevel.Trace)
                .AddDebug(LogLevel.Trace);

            var logger = loggerFactory.CreateLogger(typeof(Program));
            logger.LogInformation("Information");
            logger.LogTrace("Trace");
            logger.LogDebug("Debug");
            logger.LogWarning("Warning");
            logger.LogCritical("Critical");
            logger.LogError("Error");
            Console.ReadKey();
            return 0;

            }
    }

}

ServiceCollection 上使用 AddLogging() 扩展方法时,最低日志级别的默认值不同。你可以这样设置:

static void Main(string[] args)
{
    var serviceCollection = new ServiceCollection()
        .AddLogging(builder => {
            builder.SetMinimumLevel(LogLevel.Trace);
            builder.AddConsole();
            builder.AddDebug();
        });

    var serviceProvider = serviceCollection.BuildServiceProvider();
    var loggerFactory = serviceProvider.GetService<ILoggerFactory>();

    var logger = loggerFactory.CreateLogger(typeof(Program));
    logger.LogInformation("Information");
    logger.LogTrace("Trace");
    logger.LogDebug("Debug");
    logger.LogWarning("Warning");
    logger.LogCritical("Critical");
    logger.LogError("Error");
    Console.ReadKey();
}