代码之家  ›  专栏  ›  技术社区  ›  dinotom

将日志记录配置从appsettings绑定到POCO Asp。净核心2

  •  2
  • dinotom  · 技术社区  · 7 年前

    我有一个ApplicationConfigurationSettings类,我正在绑定appsettings中的值。json文件到。我可以绑定除logger LogLevel值之外的所有内容,这很可能是因为日志条目的json格式中存在子级别。

    我将类绑定如下

     services.Configure<ApplicationConfigurationSettings>(Configuration.GetSection("ApplicationConfiguration"));
    

    应用程序设置。json(为了简洁起见删除了部分)

    {
       "ApplicationConfiguration": {
          "ConnectionStrings": {
             "DevelopmentConnection": "Server=(localdb)\\mssqllocaldb;Database=TestingConfigurationNetCoreTwo_Development;Trusted_Connection=True;MultipleActiveResultSets=true"       
            },
            "Logging": {
               "IncludeScopes": false,
               "LogLevel": {
                  "Default": "Warning"
             }
           },
           "ApplicationIconUrls": {
               "MaleUserIcon": "https://machineryrestorations.blob.core.windows.net/publicfiles/images/BestMaleUser_32x32.png",
               "FemaleUserIcon": "https://machineryrestorations.blob.core.windows.net/publicfiles/images/BestFemaleUser_32x32"
          },   
          "ApplicationInfo": {
              "VersionNumber": "1.0.0",
              "Author": "Jimbo",
              "ApplicationName": "CustomTemplate",
              "CreatedOn": "November 20, 2017"
    
            }
        }
    }
    

    我的记录器POCO

    public class LoggerSettings
    {
        public bool IncludeScopes { get; set; }
        public KeyValuePair<string,string> LogLevel { get; set; }
    }
    

    我确信这是由于绑定器无法将我的LogLevel属性与json文件中的内容相协调。既然我无法更改json文件中的日志格式,我如何更改记录器POCO以使其工作?

    这是json提供程序在检查来自

    services.AddSingleton(Configuration);
    

    {[ApplicationConfiguration:Logging:IncludeScopes,False]}{[ApplicationConfiguration:Logging:LogLevel:Default,Warning]}

    我似乎无法在类中正确设置该属性,使其正确绑定。

    1 回复  |  直到 7 年前
        1
  •  1
  •   CodeFuller    7 年前

    Json对象

    "LogLevel": {
      "Default": "Warning"
    }
    

    无法映射到 public KeyValuePair<string,string> LogLevel { get; set; } 原因很简单。如果一段时间后,该部分将扩展为另一个字段:

    "LogLevel": {
      "Default": "Warning",
      "SomeOtherField": "SomeValue"
    }
    

    它应该如何映射到单个 KeyValuePair<string,string> ? 当然,在您的简单情况下,这样的单键值对象可能会被潜在映射,但configuration binder在其假设中并没有走那么远,它只是不以这种方式工作。

    我认为这是一件好事,因为你试图从强类型的POCO转换到一些键值包,这在某种程度上降低了强类型配置的整体价值。净核心。

    解决你的问题很简单。只需声明 LoggingLevel 使用单个(此时)属性初始化 Default 属于 string 类型:

    public class LoggingLevel
    {
        public string Default { get; set; }
    }
    
    public class LoggerSettings
    {
        public bool IncludeScopes { get; set; }
    
        public LoggingLevel LogLevel { get; set; }
    }
    

    您可以再进一步设置 违约 属性为 Microsoft.Extensions.Logging.LogLevel . 配置绑定器将正确映射字符串值,如 "Warning" 到枚举值 LogLevel.Warning :

    public class LoggingLevel
    {
        public LogLevel Default { get; set; }
    }
    

    拥有如此简单的POCO似乎有些过头了,对于高级配置,您将拥有相当多的POCO。但这实际上是一条路,强类型、显式和可扩展。

    推荐文章