在控制台应用程序中找到有关 .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>
Run Code Online (Sandbox Code Playgroud)
代码
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");
}
}
Run Code Online (Sandbox Code Playgroud)
您的配置是正确的,提供程序只是在退出主线程之前没有足够的时间来刷新输出:
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();
}
}
Run Code Online (Sandbox Code Playgroud)
此外,我认为您不需要,.AddTransient<Program>()除非您打算创建多个Program实例。
| 归档时间: |
|
| 查看次数: |
7527 次 |
| 最近记录: |