0

我正在尝试将日志记录添加到现有的 .NET Framework 应用程序。我添加了自己的记录器(称为 MyLogger)并将配置设置放入 appsettings.json,如下所示:

{
  "LogFilePath": "C:\\Temp\\Logs\\%yyyy-%MM-%dd.txt",
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning"
    },
    "MyLogger": {
      "LogLevel": {
        "Default": "Error"
      }
    }
  }
}

我可以像这样读取配置设置:

IConfigurationBuilder configurationBuilder = new ConfigurationBuilder()
    .AddJsonFile("appsettings.json");

var configuration = configurationBuilder.Build();

我想保持简单,不使用主机。我可以像这样创建 LoggerFactory:

var loggerFactory = LoggerFactory.Create(loggingBuilder =>
{
    loggingBuilder
        .ClearProviders()
        .AddMyLogger(loggerConfig =>
        {
            loggerConfig.FilePath = configuration["LogFilePath"];
        });
});
ILogger logger = loggerFactory.CreateLogger("Global");
logger.LogInformation("Application starting");

如何将 appsettings.json 中的配置设置连接到 LoggerFactory?例如,在上面的代码中,LogInformation() 不应该记录任何内容,因为我的 appsettings.json 将 MyLogger 的最低日志级别设置为 Error。

4

1 回答 1

0

有一个名为 AddConfiguration() 的扩展方法,但您需要参考:

using Microsoft.Extensions.Configuration;

所以代码看起来像这样:

//Create logger factory
var loggerFactory = LoggerFactory.Create(loggingBuilder =>
{
    loggingBuilder
        .ClearProviders()
        .AddConfiguration(configuration.GetSection("Logging"))
        .AddMyLogger(loggerConfig =>
        {
            loggerConfig.FilePath = configuration["LogFilePath"];
        });
});

//Create logger
ILogger logger = loggerFactory.CreateLogger("Global");
logger.LogInformation("Application starting");

此外,为记录器提供程序名称起别名,如下所示:

[ProviderAlias("My")]
public sealed class MyLoggerProvider : ILoggerProvider
{ ... }

然后在 appsettings.json 中,您可以使用别名“My”将过滤器应用于您的记录器提供程序:

{
  "LogFilePath": "C:\\Temp\\Logs\\%yyyy-%MM-%dd.txt",
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning"
    },
    "My": {
      "LogLevel": {
        "Default": "Debug",
        "Microsoft": "Warning"
      }
    }
  }
}
于 2021-12-27T04:31:39.617 回答