8

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'"
}
}

3 Answers 3

10

You need to use Serilog.Expressions for this:

Install-Package Serilog.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.

1
  • Will overrides work if you want to, say, have different namespaces write to different files? e.g namespace foo -> foo.log and namespace bar -> bar.log.
    – Mike Loux
    Aug 10, 2022 at 19:21
1

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.

0

It is way easier to do using Filter.ByIncludingOnly your "MyWellKnownNamespace" That's way easier than trying to figure out exactly what namespace the unwanted messages are coming from:

 Log.Logger = new LoggerConfiguration()
                .ReadFrom.Configuration(_configuration)
                .Filter.ByIncludingOnly( Matching.FromSource("MyWellKnownNamespace") )
                .CreateLogger();

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.