Warm tip: This article is reproduced from serverfault.com, please click

c#-登录.Net核心控制台应用程序不起作用

(c# - Logging in .Net core console application not working)

发布于 2018-07-13 13:37:38

我正在关注本教程:https : //andrewlock.net/using-dependency-injection-in-a-net-core-console-application/

并因此安装了软件包,但日志未在任何地方打印。

这是我的代码:

  var serviceProvider = new ServiceCollection()
            .AddLogging()
            .AddTransient<IFoo, Foo>(s =>
            {
                return new Foo()})
            .BuildServiceProvider();

            //configure console logging
            serviceProvider
                .GetService<ILoggerFactory>()
                .AddConsole(LogLevel.Debug);

 var logger = serviceProvider.GetService<ILoggerFactory>().CreateLogger<Program>();

            logger.LogError("Starting application");
Questioner
Mrug
Viewed
11
Celal Yildirim 2018-07-14 00:44:47

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

你可以在Main函数的末尾添加

serviceProvider.Dispose();

或者你可以添加.AddDebug()

            serviceProvider
            .GetService<ILoggerFactory>()
            .AddConsole(LogLevel.Debug)
            .AddDebug();