C# 配置日志记录

2f44bdee6971bab107fb7d1a1737a5d4.png

在 .NET Core 中,可以给配置文件使用提供程序,例如从 JSON 或 XML文件、环境变量或命令行参数中读取配置。只需要从 NuGet 包 Microsoft.ExtensionsConfiguration 中创建一个ConfigurationBuilder,并向此构建器添加提供程序。要添加 JSON 提供程序,需要调用扩展方法 AddJsonFile。构建器的 Build 方法返回一个实现 IConfiguration 的对象。可以使用此接口通过任何已配置的提供程序来访问已配置值。下面的示例代码从配置中检索 Logging 部分,并将其传递给 RegisterServices 方法:

var configurationBuilder = new ConfigurationBuilder() ;
configurationBuilder.AddJsonFile("appsettings.json");
IConfiguration configuration = configurationBuilder.Build();
RegisterServices(configuration);

4e317a0ed8487b228fec49c143392602.png

示例应用程序的配置文件根据提供程序和类别配置不同的配置值。对于 Debug 提供程序,LogLevel 设置为 Information。这样,对于所有类别,Information及以上级别都记录到 Visual Studio 的 Output 窗口。对于 Console 提供程序,LogLevel 根据类别的不同而不同。在 Console 提供程序的配置之下,所有其他提供程序的默认配置都是基于类别用特定的日志级别定义:

{
  "Logging":  {
    "Debug":  {
      "LogLevel": "Information"
    },
   "Console":  {
     "LogLevel":  {
       "LoggingConfigurationSample.SampleController": "Information",
         "Default": "Warning"
      }
    },
    "LogLevel":  {
      "Default": "Warning",
      "System": "Information",
      "LoggingConfigurationSample.SampleController": "Warning"
    }
  }
}

297663eef9e5167dd8153752544f290f.png

在日志配置就绪后,现在调用 AddConfiguration 方法,以传递对IConfiguration 对象的引用。AddConfiguration 方法需要配置文件中 Logging部分的内容:

static void RegisterServices(IConfiguration configuration)
{
  var services = new ServiceCollection(); 
  services.AddLogging(builder =>
  {
    builder.AddConfiguration(configuration.GetSection("Logging"))
      .AddConsole(); 
#if DEBUG
    builder.AddDebug(); 
#endif
  });
  services.AddScoped<SampleControler>();
  AppServices = services.BuildServiceProvider();
}

3d55e1893863e0944da10c0c0c4fe180.png

注意:

Microsoft.Extensions.Configuration 的体系结构和使用不同的配置提供程序。

a08f4adff63dadc7e0413aaf1a774a7b.png

0806ad24b1ab218fbc39c30a2812e49d.png

 微信公众号 

DotNet讲堂

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值