How to use filter with Serilog.Sinks.EventLog

110 views Asked by At

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:

  • .Net 8
  • Serilog.AspNetCore v8.0.0
  • SerilogExpressions v4.0.0
  • Serilog.Sinks.EventLog v3.1.0

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

1

There are 1 answers

0
Chinmay T On BEST ANSWER

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