Expression-based event filtering for Serilog.
Deprecation notice: this package has been replaced by Serilog.Expressions, which provides an improved implementation of the functionality that was covered here.
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();Install Serilog.Filters.Expressions from NuGet:
Install-Package Serilog.Filters.ExpressionsAdd Filter.ByIncludingOnly(fiterExpression) or Filter.ByExcluding(fiterExpression) calls to LoggerConfiguration.
The syntax is based on SQL, with added support for object structures, arrays, and regular expressions.
| Category | Examples |
|---|---|
| Literals | 123, 123.4, 'Hello', true, false, null |
| Properties | A, A.B, @Level, @Timestamp, @Exception, @Message, @MessageTemplate, @Properties['A-b-c'] |
| Comparisons | A = B, A <> B, A > B, A >= B, A is null, A is not null, A in [1, 2] |
| Text | A like 'H%', A not like 'H%', A like 'Hel_o', Contains(A, 'H'), StartsWith(A, 'H'), EndsWith(A, 'H'), IndexOf(A, 'H'), Length(A) |
| Regular expressions | A = /H.*o/, Contains(A, /[lL]/), other string functions |
| Collections | A[0] = 'Hello', A[?] = 'Hello' (any), StartsWith(A[*], 'H') (all), Length(A) |
| Maths | A + 2, A - 2, A * 2, A % 2 |
| Logic | not A, A and B, A or B |
| Grouping | A * (B + C) |
| Other | Has(A), TypeOf(A) |
Using Serilog.Settings.AppSettings:
<add key="serilog:using:FilterExpressions" value="Serilog.Filters.Expressions" />
<add key="serilog:filter:ByExcluding.expression" value="Name = 'World'" />Using Serilog.Settings.Configuration:
{
"Serilog": {
"Using": ["Serilog.Settings.Configuration"],
"Filter": [
{
"Name": "ByExcluding",
"Args": {
"expression": "EndsWith(RequestPath, '/SomeEndpoint')"
}
}
]