serilogserilog-aspnetcoreserilog-expressions

How to use filter with Serilog.Sinks.EventLog


I'm really not sure what I'm missing. Filtering is not working at all for Serilog.Sinks.EventLog. Everything gets logged no matter what I've tried in the Filter configuration. I've used old syntax, new sytanx, different properties, etc. for the expression.

Does EventLog support filters and if so, how do I fix this?

Here's an excerpt from my appsettings.json file.

...
        {
                "Name": "EventLog",
                "Filter": [
                    {
                        "Name": "ByIncludingOnly",
                        "Args": {
                            "expression": "Contains(@Message, 'EventLog:')"
                        }
                    }
                ],

                "Args": {
                    "source": "WebUI Application",
                    "logName": "Application",
                    "manageEventSource": true,
                    "restrictedToMinimumLevel": "Verbose",
                    "levelSwitch": "$controlSwitch"
                }
        }
...

Configuration:

I've tried various configurations for the expression, old syntax, new syntax, etc. to no avail.


Solution

  • Adding below code into program.cs works and only creates event logs for log level 'Error'. I have below example from a sample console app with .Net8. Here is the github repo link with this example and some other examples on Serilog usage in different type of .Net projects.

    Log.Logger = new LoggerConfiguration()
                .MinimumLevel.Debug()            
                .WriteTo.Logger( lev => lev
                .Filter.ByIncludingOnly( l => l.Level == LogEventLevel.Error)
                .WriteTo.EventLog("SerilogConsoleApp.Eample", manageEventSource:true))
    .CreateLogger();
    

    enter image description here

    I noticed that you have wrong config structure, Try changing your appsettings.json with below config and see.

    {
      "Name": "EventLog",
      "Args": {
        "source": "SerilogConsoleApp.Eample",
        "logName": "SerilogConsoleApp",
        "manageEventSource": true,
        "filter": [
          {
            "Name": "ByIncludingOnly",
            "Args": {
              "expression": "Level = 'Error'"
            }
          }
        ]
      }
    }