登录 .Net 核心控制台应用程序不起作用
问题描述:
我正在学习本教程:https://andrewlock.net/using-dependency-injection-in-a-net-core-console-application/
并相应地安装了软件包,但没有在任何地方打印日志.
and accordingly installed the packages but log is not getting printed anywhere.
这是我的代码:
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");
答
事实证明,控制台日志记录提供程序不会像在 net-core-1.x 版本中那样立即将消息刷新到控制台.它似乎在不同的线程上运行.有关信息,请参阅此网页:https://github.com/aspnet/Logging/issues/631
Turns out the console logging provider doesn't immediately flush the messages to the console like it did in the net-core-1.x versions. It appears to run on a different thread. See this web page for info: https://github.com/aspnet/Logging/issues/631
您可以在Main函数的末尾添加.
You can add at the end of the Main function.
serviceProvider.Dispose();
或者你可以添加.AddDebug()
serviceProvider
.GetService<ILoggerFactory>()
.AddConsole(LogLevel.Debug)
.AddDebug();