Serilog : how do you specify a filter expression in config file

倖福魔咒の 提交于 2020-03-01 03:37:07

问题


I am trying to specify this filter in the appsettings .json file

.Filter.ByExcluding(Matching.FromSource("Microsoft.AspNetCore.Hosting.Internal.WebHost"))

The above syntax works when specified in c#

But trying to specify the same in a json file does not work.

"Filter": [
{
"Name": "ByExcluding",
"Args": {
"expression": "Matching.FromSource = 'Microsoft.AspNetCore.Hosting.Internal.WebHost'"
}
}

回答1:


You need to use Serilog.Filters.Expressions for this:

Install-Package Serilog.Filters.Expressions

The filter section in appsettings.json looks like:

"Filter": [
  {
    "Name": "ByExcluding",
    "Args": {
      "expression": "SourceContext = 'Microsoft.AspNetCore.Hosting.Internal.WebHost'"
    }
  }
],

In this specific case, I'd suggest considering level overrides as an alternative that will turn off a specific namespace more efficiently.




回答2:


The answer by Nicholas Blumhardt is correct, but there are some extra details that you might find useful. If you do not have a piece of source code like the following (during serilog initialization)

.Filter.ByExcluding(Matching.FromSource("Microsoft.AspNetCore.Hosting.Internal.WebHost"))

in one of your .cs files, then the Serilog.Filters.Expressions.dll file will not be loaded, and your filter expression will just fail silently when the config file is loaded. So be sure to refer to .Filter in your .cs source (even if it never gets called)

Another item that is useful for debugging serilog itself (especially config file start ups like this example) is to add serilog debugging of itself to the console

   // this is just to check on serilog startup and configuration, problems with serilog itself get written to console
    Serilog.Debugging.SelfLog.Enable(msg => Console.WriteLine(msg));

Then run your .cs app in debug mode and check for messages on the console as you initialize serilog from its config file.



来源:https://stackoverflow.com/questions/44025992/serilog-how-do-you-specify-a-filter-expression-in-config-file

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!