serilogserilog-filter

Is it possible to filter out properties of serilog events based on the logging level


In Serilog we can filter out events based on either logging levels or using the serilog expressions.

"Serilog": {
    "MinimumLevel": {
      "Default": "Debug"
    },

I am wondering if it is possible to filter out properties of events too based on the logging level. We have this scenario where we want to log communication details. Most of the time communication text as ASCII is good enough, but sometime hex format would be helpful. I am hoping that we can log hex format property only when the logging level is Verbose. Is it possible?

Event
{
  "ascii": "Hello World
",
  "hex": "48 65 6c 6c 6f 20 57 6f 72 6c 64 0d 0a"
}

Solution

  • You can accomplish this by adding a custom destructuring policy to transform the event. Grab the current log level. Detect if Verbose is enabled. If it is, you return an object containing the hex values. If it's not, you return an object that doesn't contain the hex values. Here's a working example:

    using System;
    using Serilog;
    using Serilog.Events;
    
    namespace HelloConsoleCore
    {
        class MyEventToLog
        {
            public string SomeText { get; set; }
    
            public string SomeHex { get; set; }
        }
    
        class Program
        {
            static void Main(string[] args)
            {
                Log.Logger = new LoggerConfiguration()
                    //.MinimumLevel.Verbose //change your minimum level to see the effect
                    .MinimumLevel.Debug()
                    .WriteTo.Console()
                    .Destructure.ByTransforming((MyEventToLog ev) => {
    
                        if (Log.IsEnabled(LogEventLevel.Verbose))
                        {
                            return new { ev.SomeHex, ev.SomeText };
                        }
    
                        return new { ev.SomeText };
                        })
                    .CreateLogger();
    
                var eventIWantToLog = new MyEventToLog
                {
                    SomeHex = "48 65 6c 6c 6f 20 57 6f 72 6c 64 0d 0a",
                    SomeText = "Hello World"
                };
    
                Log.Information("Let's log an event... {@EventIWantToLog}", eventIWantToLog);
    
                Console.WriteLine("Press any key to exit");
                Console.ReadKey();
            }
        }
    }