从 Microsoft 进行迁移。日志记录2.1 到2.2 或3。0Migrate from Microsoft.Extensions.Logging 2.1 to 2.2 or 3.0

本文内容

本文概述了迁移使用2.1 到2.2 或 3.0 Microsoft.Extensions.Logging 的 non-ASP.NET 核心应用程序的常见步骤。

2.1 到 2.22.1 to 2.2

手动创建 ServiceCollection 并调用 AddLogging

2.1 示例:

  1. using (var loggerFactory = new LoggerFactory())
  2. {
  3. loggerFactory.AddConsole();
  4. // use loggerFactory
  5. }

2.2 示例:

  1. var serviceCollection = new ServiceCollection();
  2. serviceCollection.AddLogging(builder => builder.AddConsole());
  3. using (var serviceProvider = serviceCollection.BuildServiceProvider())
  4. using (var loggerFactory = serviceProvider.GetService<ILoggerFactory>())
  5. {
  6. // use loggerFactory
  7. }

2.1 至3。02.1 to 3.0

在3.0 中,使用 LoggingFactory.Create

2.1 示例:

  1. using (var loggerFactory = new LoggerFactory())
  2. {
  3. loggerFactory.AddConsole();
  4. // use loggerFactory
  5. }

3.0 示例:

  1. using (var loggerFactory = LoggerFactory.Create(builder => builder.AddConsole()))
  2. {
  3. // use loggerFactory
  4. }

其他资源Additional resources

.NET Core 和 ASP.NET Core 中的日志记录