我们想获取日志:
所有这些都在 appsettings.json 中配置。
这是应用程序的 appsettings.json 文件:
{
"Serilog": {
"Using": [ "Serilog.Sinks.Literate", "Serilog.Sinks.File", "Serilog.Filters.Expressions" ],
"MinimumLevel": "Verbose",
"WriteTo": [
{
"Name": "LiterateConsole"
},
{
"Name": "File",
"Args": {
"path": "%TEMP%\\Logs\\FileWithoutFilter-.log",
"outputTemplate": "{Timestamp:yyyy-MM-dd HH:mm:ss.fff} [{Level:u3}] {Message:lj}{NewLine}{Exception}",
"rollingInterval": "Day"
}
},
{
"Name": "File",
"Args": {
"path": "%TEMP%\\Logs\\UPLOADERROR-.log",
"outputTemplate": "{Timestamp:yyyy-MM-dd HH:mm:ss.fff} [{Level:u3}] {Message:lj}{NewLine}{Exception}"
},
"Filter": [
{
"Name": "ByIncludingOnly",
"Args": {
"expression": "@Level = 'Error' and UploadError is not null"
}
}
]
}
]
}
}
但是,尽管控制台和文件(无过滤)运行良好,带过滤的文件正在记录所有行,就像文件(无过滤)一样。
我们在 C# 代码中发送这个 log.error 行:
Log.Error("Fichero con error {@UploadError}", true);
但是,我说过,所有行都记录到 UPLOADERROR 文件中
知道 appsettings.file 有什么问题吗?
问候。
最佳答案
解决方案是使用带有 serilog 的子记录器。然后,您必须使用过滤器和接收器配置子记录器。
仔细阅读与常规、配置和过滤器相关的 serilog 文档是诀窍。
{
"Serilog": {
"Using": [ "Serilog.Sinks.Literate", "Serilog.Sinks.File", "Serilog.Filters.Expressions" ],
"MinimumLevel": "Verbose",
"WriteTo": [
{
"Name": "LiterateConsole"
},
{
"Name": "File",
"Args": {
"path": "%TEMP%\\Logs\\FileWithoutFilter-.log",
"outputTemplate": "{Timestamp:yyyy-MM-dd HH:mm:ss.fff} [{Level:u3}] {Message:lj}{NewLine}{Exception}",
"rollingInterval": "Day"
}
},
{
"Name": "Logger",
"Args": {
"configureLogger": {
"Filter": [
{
"Name": "ByIncludingOnly",
"Args": {
"expression": "@Level = 'Error' and UploadError is not null"
}
}
],
"WriteTo": [
{
"Name": "File",
"Args": {
"path": "%TEMP%\\Logs\\UPLOADERROR-.log",
"outputTemplate": "{Timestamp:yyyy-MM-dd HH:mm:ss.fff} [{Level:u3}] {Message:lj}{NewLine}{Exception}"
}
}
]
}
}
}
]
}
}
使用以前的配置,现在一切正常。
关于logging - 来自 appsettings.json 中 Filters.Expressions 的 Serilog 和过滤器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49315287/