serilog / serilog-extensions-logging

Serilog provider for Microsoft.Extensions.Logging
Apache License 2.0
309 stars 99 forks source link

Log filtering seems to be ignored due to override #147

Closed dpoole73 closed 4 years ago

dpoole73 commented 5 years ago

I've been trying to use the AddSerilog() extension method to add Serilog logging in my builder but found that any filtering I apply is overridden in the extension method, for example:

services.AddLogging(l => l.AddFilter((cat, lev) => 
                { 
                    // Filter information logs from Sample.Program
                    if (cat.StartsWith("Sample.Program"))
                    {
                        return lev >= LogLevel.Warning;
                    }
                    // else informational only
                    return lev >= LogLevel.Information;
                })
                .AddConsole()
                );

then

    logger.LogInformation("Information");
    logger.LogWarning("Warning");

displays only the warning message:

warn: Sample.Program[0]
      Warning

If I add .AddSerilog() like this:

services.AddLogging(l => l.AddFilter((cat, lev) => 
                { 
                    // Filter out all EF logs to stop it being so chatty
                    if (cat.StartsWith("Sample.Program"))
                    {
                        return lev >= LogLevel.Warning;
                    }
                    // else informational only
                    return lev >= LogLevel.Information;
                })
                .AddConsole()
                .AddSerilog()
                );

I see both messages from the serilog logger and only the warning message from the .net logger:

[08:47:47 INF] Information
[08:47:49 WRN] Warning
warn: Sample.Program[0]
      Warning

this seems to be due to this this line If I comment that line out then filtering works as expected. Was this left for debugging purposes? Should it be controlled via a parameter to the method? It doesn't seem like it is needed since you can control filtering outside.

nblumhardt commented 5 years ago

Hi @dpoole73 - thanks for the note.

You can read some of the discussion regarding this in https://github.com/serilog/serilog-extensions-logging/issues/98.

The eventual result of working through this was Serilog.AspNetCore's UseSerilog() and the related instructions in that README; see alternatively Serilog.Extensions.Hosting if you're not in a web app.

If your app's a plain console app, then configuring everything via Serilog (sinks, levels, filters, etc.) and just using Microsoft.Extensions.Logging as a logging abstraction will be a better experience. Let us know if you need more details on this.

Cheers, Nick