gpt4 book ai didi

c# - .Net Core 控制台日志记录未出现

转载 作者:行者123 更新时间:2023-12-05 01:34:40 26 4
gpt4 key购买 nike

找到这个 article在 .Net 上登录控制台应用程序,但它对我不起作用。示例日志未出现在控制台中。

我正在使用最新的日志包

引用资料

  <ItemGroup>
<PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="3.1.7" />
<PackageReference Include="Microsoft.Extensions.Logging" Version="3.1.7" />
<PackageReference Include="Microsoft.Extensions.Logging.Console" Version="3.1.7" />
</ItemGroup>

代码

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

class Program
{
static void Main(string[] args)
{
// instantiate DI and configure logger
var serviceProvider = new ServiceCollection()
.AddLogging(cfg => cfg.AddConsole())
.AddTransient<Program>()
.Configure<LoggerFilterOptions>(cfg => cfg.MinLevel = LogLevel.Information)
.BuildServiceProvider();
// get instance of logger
var logger = serviceProvider.GetService<ILogger<Program>>();
// use the logger
logger.LogInformation("Woo Hooo");
}
}

enter image description here

最佳答案

您的配置是正确的,提供者只是没有足够的时间在您退出主线程之前刷新输出:

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

class Program
{
static void Main(string[] args)
{
// instantiate DI and configure logger
var serviceProvider = new ServiceCollection()
.AddLogging(cfg => cfg.AddConsole())
.AddTransient<Program>()
.Configure<LoggerFilterOptions>(cfg => cfg.MinLevel = LogLevel.Information)
.BuildServiceProvider();
// get instance of logger
var logger = serviceProvider.GetService<ILogger<Program>>();
logger.LogInformation("Woo Hooo");

// This will allow enough time to flush
Console.ReadLine();
}
}

enter image description here

此外,我认为您不需要 .AddTransient<Program>()除非你打算创建多个 Program实例。

关于c# - .Net Core 控制台日志记录未出现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63635454/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com