serilog

Filter by phrase possible?


Kinda new to serilog, but wanted to do something very simple, like:

            Log.Logger = new LoggerConfiguration()
                .MinimumLevel.Information()
                .Filter.ByExcluding("Could not find file")
                .WriteTo.File("SimplePlayerApartment-.log", rollingInterval: RollingInterval.Day, retainedFileCountLimit: 1)
                .CreateLogger();

I figured Filter.ByExcluding would allow me to not log lines with certain keywords/phrases in it. Instead, whatever documentation I can find, it seems to excluse based on namespace, classes, and all sorts of fancy things, whereas all I want is to filter out a simple string or 2.

Is there even any way of doing what I want? As the above code example throws a big fat runtime error.


Solution

  • Filter.ByExcluding is a predicate Func<LogEvent, bool>, so you need to give it a function that returns if the log event should be excluded or not...

    Log.Logger = new LoggerConfiguration()
        .MinimumLevel.Information()
        .Filter.ByExcluding(e => e.MessageTemplate.Text.Contains("Could not find file")) // <#<#<#<
        .WriteTo.File("SimplePlayerApartment-.log", rollingInterval: RollingInterval.Day, retainedFileCountLimit: 1)
        .CreateLogger();
    
    var fileName = "file.ext";
    
    Log.Information("Hello");
    Log.Information("Could not find file {fileName}", fileName); // Excluded from the log
    Log.Information("Bye");
    

    It's worth to mention that the example above applies the filter based on the message template which is (as it implies) the template before rendering, so e.MessageTemplate.Text would be Could not find file {fileName} instead of Could not find file file.ext.