One of the lesser known features inside Serilog is the support for filter expressions. This gives you a SQL like syntax to filter your log messages.
To enable this feature you have to install the Serilog.Filters.Expressions nuget package.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var expr = "@Level = 'Information' and AppId is not null and Items[?] like 'C%'"; | |
Log.Logger = new LoggerConfiguration() | |
.Enrich.WithProperty("AppId", 10) | |
.Filter.ByIncludingOnly(expr) | |
.WriteTo.Console() | |
.CreateLogger(); | |
// Printed | |
Log.Information("Cart contains {@Items}", new[] { "Tea", "Coffee" }); | |
Log.Information("Cart contains {@Items}", new[] { "Peanuts", "Chocolate" }); | |
// Not printed | |
Log.Warning("Cart contains {@Items}", new[] { "Tea", "Coffee" }); | |
Log.Information("Cart contains {@Items}", new[] { "Apricots" }); | |
Log.CloseAndFlush(); |
More information: https://nblumhardt.com/2017/01/serilog-filtering-dsl/