Home

Awesome

Serilog.Filters.Expressions Build status NuGet Release

Expression-based event filtering for Serilog.

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();

Getting started

Install Serilog.Filters.Expressions from NuGet:

Install-Package Serilog.Filters.Expressions

Add Filter.ByIncludingOnly(fiterExpression) or Filter.ByExcluding(fiterExpression) calls to LoggerConfiguration.

Syntax

The syntax is based on SQL, with added support for object structures, arrays, and regular expressions.

CategoryExamples
Literals123, 123.4, 'Hello', true, false, null
PropertiesA, A.B, @Level, @Timestamp, @Exception, @Message, @MessageTemplate, @Properties['A-b-c']
ComparisonsA = B, A <> B, A > B, A >= B, A is null, A is not null, A in [1, 2]
TextA 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 expressionsA = /H.*o/, Contains(A, /[lL]/), other string functions
CollectionsA[0] = 'Hello', A[?] = 'Hello' (any), StartsWith(A[*], 'H') (all), Length(A)
MathsA + 2, A - 2, A * 2, A % 2
Logicnot A, A and B, A or B
GroupingA * (B + C)
OtherHas(A), TypeOf(A)

XML <appSettings> configuration

Using Serilog.Settings.AppSettings:

  <add key="serilog:using:FilterExpressions" value="Serilog.Filters.Expressions" />
  <add key="serilog:filter:ByExcluding.expression" value="Name = 'World'" />

JSON appSettings.json configuration

Using Serilog.Settings.Configuration:

{
  "Serilog": {
    "Using": ["Serilog.Settings.Configuration"],
    "Filter": [
      {
        "Name": "ByExcluding",
        "Args": {
          "expression": "EndsWith(RequestPath, '/SomeEndpoint')"
        }
      }
    ]