Serilog Per Sink Filters

Posted
7/13/2023
Tags
Programming
C#

It's helpful to have all log events sent to the console to make development easier, but it's best to not have other logging sinks spammed with debug and verbose level logs.

Methods that don't work

A working method

A way that actually works is to use .Filter in a sub-logger:

loggerConfiguration
	.WriteTo.Logger(lc => lc
		// These are things like "CTRL+C to exit" messages
		// Use a sub-logger to let them go to the console, but not to the DB
		.Filter.ByExcluding(le => Matching.FromSource("Microsoft").Invoke(le)
			&& (le.Level == LogEventLevel.Verbose
				|| le.Level == LogEventLevel.Debug
				|| le.Level == LogEventLevel.Information))
		.WriteTo.Whatever())
	.WriteTo.Console();