净核心不登录到控制台

netcore not logging to console

我有一个简单的测试项目来试验使用 Microsoft 日志记录扩展程序包使用 NetCore 2.0 进行日志记录。

我遇到的问题是,当我第一次 运行 我的应用程序时,它会按预期记录信息性消息。我遇到的奇怪行为是后续的 运行s 根本不会产生任何消息。

我的项目以 Net Core 2.0 框架为目标,并安装了以下 NuGet 包:

下面是我尝试使用日志记录的示例代码:

using System;

namespace LoggingNetCore2
{
    using Microsoft.Extensions.Logging;

    class Program
    {
        static void Main(string[] args)
        {
            var loggerFactory = new LoggerFactory();
            loggerFactory.AddConsole();
            loggerFactory.AddDebug(); // <-- why is this needed for console logging?

            var logger = loggerFactory.CreateLogger(typeof(Program));
            logger.LogInformation("Hello, World!");
            logger.LogTrace("trace");
            logger.LogDebug("debug");
            logger.LogWarning("warning");
            logger.LogCritical("critical");
            logger.LogError("errrrr");

            //using (logger.BeginScope("MyMessages"))
            //{
            //    logger.LogInformation("Beginning Operation...");
            //    logger.LogInformation("Doing something cool... please wait.");
            //    logger.LogInformation("Completed successfully.");
            //}
        }
    }
}

当我 运行 以上时,我在控制台 window 上没有输出。 spring 对可能发生的事情有什么想法吗?

我尝试过的事情:

编辑: 如果我将调试日志提供程序添加到组合中,我现在会在控制台中显示日志 window。

在 NetCore 1.x 应用程序中,只需添加控制台提供程序就足够了。

编辑 #2: 事实证明,控制台日志记录提供程序不会像在 net-core-1.x 版本中那样立即将消息刷新到控制台.它似乎 运行 在不同的线程上。有关信息,请参阅此网页:https://github.com/aspnet/Logging/issues/631

@ajawad987,你是对的。 Dispose() 有效。

public class Program
{
    public static void Main(string[] args)
    {
        var services = new ServiceCollection()
            .AddLogging(config => config.AddConsole())
            .BuildServiceProvider();

        services.GetRequiredService<ILogger<Program>>()
            .LogCritical("Hello");

        ((IDisposable) services)?.Dispose();
    }
}