Skip to content

Log Filtering: Package v.2.x

Vladyslav Bardin edited this page Mar 11, 2024 · 1 revision

Overview

X.Serilog.Sinks.Telegram provides a rich filtering mechanism centered around the IFilter interface. This powerful feature allows developers to process log entries based on custom rules selectively.

Operators

The Log filter configuration supports operators AND and OR.

  • AND: All filter conditions MUST be satisfied for the log entries to pass.
  • OR: The log entries will pass if at least one filter condition is satisfied.

Interface - IFilter

The core of this feature is the IFilter interface.

public interface IFilter 
{
    bool Filter(LogEntry entry);
}

The Filter method accepts a LogEntry object and returns a boolean value indicating whether the log should be delivered.

Pre-defined Filters

LogMessageContainsFilter

This filter passes a log entry if the entry's message contains a specific string. String check is case-insensitive.

public class LogMessageContainsFilter : IFilter
{
    public LogMessageContainsFilter(string keyWord) { /* Implementation */ }

    public bool Filter(LogEntry entry) { /* Implementation */ }
}

LogMessageNotContainsFilter

This filter passes a log entry if the entry's message does not contain a specific string. String check is case-insensitive.

public class LogMessageNotContainsFilter : IFilter
{
    public LogMessageNotContainsFilter(string keyWord) { /* Implementation */ }

    public bool Filter(LogEntry entry) { /* Implementation */ }
}

Creating a Custom Log Filter

To create a custom log filter, developers must implement the IFilter interface and provide a custom logic inside the Filter method.

Here's a simple example of a custom filter that only allows log entries with severity of Warning or above.

public class SeverityFilter : IFilter
{
    public bool Filter(LogEntry entry)
    {
        return (entry.Severity >= Severity.Warning);
    }
}

Applying Filters

Filters can be set through the configuration system via the Filters property. The property accepts an array of filter instances; each will be applied to the logging system based on the operator defined in the configuration.

// Create filters
IFilter filter1 = new LogMessageContainsFilter("Error");
IFilter filter2 = new SeverityFilter();

// Set filter configuration
logFiltersConfiguration.Filters = new[] { filter1, filter2 }.ToImmutableList();

Note: In the above example, if the operator is AND, filter1 and filter2 must be satisfied for a log entry to pass. If the operator is OR, only one of the filters needs to be satisfied. We hope this makes using our Log Filtering feature clear and straightforward. Happy coding!