鉴于这两个类
public class SerilogSubLoggerConfigurations
{
public List<SerilogSubLoggerConfiguration> SerilogConfigurations { get; set; }
}
public class SerilogSubLoggerConfiguration
{
private string _pathFormat;
public LogEventLevel Level { get; set; }
public string PathFormat
{
get => _pathFormat;
set => _pathFormat = value.Replace("%APPLICATION_NAME%", Environment.GetEnvironmentVariable("APPLICATION_NAME"));
}
}
和一个看起来像这样的apssettings.json部分
"Serilog": {
"SubLogger": [
{
"Level": "Information",
"pathFormat": "C:/Logs/Serilog/%APPLICATION_NAME%/Information/log-{Date}.log"
},
{
"Level": "Warning",
"pathFormat": "C:/Logs/Serilog/%APPLICATION_NAME%/Warning/log-{Date}.log"
},
{
"Level": "Critical",
"pathFormat": "C:/Logs/Serilog/%APPLICATION_NAME%/Critical/log-{Date}.log"
}
],
}
我想将SubLogger
部分绑定到SerilogSubLoggerConfigurations
类。我似乎无法弄清楚如何使用这三个项目(类型为SerilogSubLoggerConfiguration
)来创建该类的配置。
答案 0 :(得分:1)
在Json配置中,子记录器对象的数组称为SubLogger
,但在配置POCO SerilogSubLoggerConfigurations
中,它被称为SerilogConfigurations
。
这就是配置绑定器无法匹配的原因。
在ASP.NET Core中,不可能(至少在这一刻)更改映射属性的名称,它们应该与配置节的名称匹配。有关详细信息,请查看此answer。
因此,您应该只重命名POCO属性或JSON部分名称。在您的情况下,SubLoggers
似乎是最合适的名称:
public class SerilogSubLoggerConfigurations
{
public List<SerilogSubLoggerConfiguration> SubLoggers { get; set; }
}
{
"Serilog": {
"SubLoggers": [
{
"Level": "Information",
"pathFormat": "C:/Logs/Serilog/%APPLICATION_NAME%/Information/log-{Date}.log"
},
{
"Level": "Warning",
"pathFormat": "C:/Logs/Serilog/%APPLICATION_NAME%/Warning/log-{Date}.log"
},
{
"Level": "Critical",
"pathFormat": "C:/Logs/Serilog/%APPLICATION_NAME%/Critical/log-{Date}.log"
}
]
}
}
IConfigurationBuilder configurationBuilder = new ConfigurationBuilder();
configurationBuilder.AddJsonFile("AppSettings.json");
IConfiguration configuration = configurationBuilder.Build();
SerilogSubLoggerConfigurations subLoggerConfigurations = configuration.GetSection("Serilog").Get<SerilogSubLoggerConfigurations>();
还有一点需要注意。 Serilog.Events.LogEventLevel
枚举不具有Critical
级别,具有Error
和Fatal
。
这就是为什么这个项目
{
"Level": "Critical",
"pathFormat": "C:/Logs/Serilog/%APPLICATION_NAME%/Critical/log-{Date}.log"
}
将无法正确加载。你应该把它改成:
{
"Level": "Error",
"pathFormat": "C:/Logs/Serilog/%APPLICATION_NAME%/Error/log-{Date}.log"
}