I'm using Serilog with a variety of sinks. One can prevent emitting the Dog
class' log events to some sink:
.Filter.ByExcluding(Matching.FromSource<Dog>())
But I can't filter by base type, e.g.:
.Filter.ByExcluding(Matching.FromAssignableSource<Animal>())
I added a feature request for such functionality.
For the time being, is there a workaround?
I found a workaround. It uses reflection but that's acceptable as a one-time operation during app start.
public abstract class Animal { }
public class Dog : Animal { }
public class Cat : Animal { }
// one-time reflection
var names =
Assembly.GetExecutingAssembly()
.GetTypes()
.Where(x => x.IsAssignableTo(typeof(Animal)))
.Where(x => x != typeof(Animal))
.Select(x => x.FullName!);
Func<LogEvent, bool> matcher = logEvent =>
names.Select(name => Matching.FromSource(name))
.Any(predicate => predicate(logEvent));
// config
.WriteTo.Logger(x => x
.Filter.ByExcluding(matcher) // or .Filter.ByIncludingOnly(matcher)
.WriteTo.Console()
)