asp.net-coreserilog.net-6.0serilog-filter

Serilog builder.Host and AddFilter


I have a a webapp using the terse .NET 6/7 serilog initialization:

var builder = WebApplication.CreateBuilder(args);

builder.Host.UseSerilog((ctx, lc) => {
  lc.WriteTo.File(
    logDir + "\\mylog.log"

  ).Filter.ByExcluding(le => {
    var s = le.RenderMessage();
    return s.StartsWith("Executing endpoint")
      || s.StartsWith("Executed endpoint")
      || s.StartsWith("User logged in.");
  });
});

I now want to filter some messages:

AddFilter("Microsoft.AspNetCore.SignalR", LogLevel.Debug);
AddFilter("Microsoft.AspNetCore.Http.Connections", LogLevel.Debug);

However I am not sure how to plug these AddFilter statements into the above builder

Any help ?


Solution

  • For a code based approach, use MinimumLevel.Override

    builder.UseSerilog(
        (ctx, lc) => lc
            .WriteTo.File(logDir + "\\mylog.log")
            .Filter.ByExcluding(le => {
                var s = le.RenderMessage();
                return s.StartsWith("Executing endpoint")
                    || s.StartsWith("Executed endpoint")
                    || s.StartsWith("User logged in.");
            })
            .MinimumLevel.Override("Microsoft.AspNetCore.SignalR", Serilog.Events.LogEventLevel.Debug)
            .MinimumLevel.Override("Microsoft.AspNetCore.Http.Connections", Serilog.Events.LogEventLevel.Debug)
        );
    

    For a configuration approach, use ReadFrom.Configuration

    builder.UseSerilog(
        (ctx, lc) => lc
            .WriteTo.File(logDir + "\\mylog.log")
            .Filter.ByExcluding(le => {
                var s = le.RenderMessage();
                return s.StartsWith("Executing endpoint")
                    || s.StartsWith("Executed endpoint")
                    || s.StartsWith("User logged in.");
            })
            .ReadFrom.Configuration(ctx.Configuration)
        );
    

    Your appsettings.json file should look something like below.
    The log levels might be different.

    {
        "Logging": {
            "LogLevel": {
                "Default": "Warning",
                "Microsoft": "Warning",
                "Microsoft.Hosting.Lifetime": "Warning"
            }
        },
        "Serilog": {
            "MinimumLevel": {
                "Default": "Warning",
                "Override": {
                    "Microsoft.AspNetCore.SignalR": "Debug",
                    "Microsoft.AspNetCore.Http.Connections": "Debug"
                }
            }
        }
    }