Serilog filter is being ignored on sub-loggers

33 views Asked by At

I have a Serilog configuration object that has been working as required but I have just added an additional sink (Email).

As such I've added sub-loggers to allow me to add a filter to each sink.

However my email sink is not observing the filter so all events are being output to it not just those with the 'EmailNotifiable' property.

n.b. I have also tried using a filter on the exception type of the event rather than the property and I get the same result.

LoggerConfiguration config = new();

config.WriteTo.Logger(x => x.Filter.ByExcluding(Matching.WithProperty("EmailNotifiable")))
      .WriteTo.Debug(restrictedToMinimumLevel: LogEventLevel.Verbose);

config.WriteTo.Logger(x => x.Filter.ByExcluding(Matching.WithProperty("EmailNotifiable")))
      .WriteTo.Console(restrictedToMinimumLevel: LogEventLevel.Verbose);

string logFilePath = CreateLogFilePath(_loggerSettings.LogFileDirectory, _loggerSettings.LogFileName);

config.WriteTo.Logger(x => x.Filter.ByExcluding(Matching.WithProperty("EmailNotifiable")))
      .WriteTo.File(logFilePath,
                    rollingInterval: RollingInterval.Day,
                    restrictedToMinimumLevel: LogEventLevel.Information,
                    shared: true);

config.WriteTo.Logger(x => x.Filter.ByIncludingOnly(Matching.WithProperty("EmailNotifiable")))
      .WriteTo.Email(_connection);

raising the log event:

_logger.ForContext("EmailNotifiable", true)
       .Warning(new EmailNotifiableException(body), message);

1

There are 1 answers

0
lazarus On

Well, after much fiddling I finally realised my mistake - I was bracketing incorrectly - effectively closing the sub-logger before defining its target.

A correct example would be:

config
    .WriteTo.Logger(c => c.Filter.ByIncludingOnly(evt => evt.Level == LogEventLevel.Verbose)
        .WriteTo.File($"{logFilePath}-VERBOSE-.log",
                      rollingInterval: RollingInterval.Day,
                      shared: true))

    .WriteTo.Logger(c => c.Filter.ByIncludingOnly(evt => evt.Level == LogEventLevel.Debug)
        .WriteTo.File($"{logFilePath}-DEBUG-.log",
                      rollingInterval: RollingInterval.Day,
                      shared: true))

    .WriteTo.Logger(c => c.Filter.ByIncludingOnly(evt => evt.Level == LogEventLevel.Information)
        .WriteTo.File($"{logFilePath}-INFO-.log",
                      rollingInterval: RollingInterval.Day,
                      shared: true))

    .WriteTo.Logger(c => c.Filter.ByIncludingOnly(evt => evt.Level == LogEventLevel.Warning)
        .WriteTo.File($"{logFilePath}-WARNING-.log",
                      rollingInterval: RollingInterval.Day,
                      shared: true))

    .WriteTo.Logger(c => c.Filter.ByIncludingOnly(evt => evt.Level == LogEventLevel.Error)
        .WriteTo.File($"{logFilePath}-ERROR-.log",
                      rollingInterval: RollingInterval.Day,
                      shared: true));