Skip to content

Batch Emitting Rules

Vladyslav Bardin edited this page Mar 11, 2024 · 3 revisions

Batch Emitting Rules in X.Serilog.Sinks.Telegram

The X.Serilog.Sinks.Telegram package enables logging with flexible batch emitting rules. This document explains how to work with these rules, provides examples for creating custom rules, and includes details about the predefined rules.

Introduction

The batch emitting rules allow users to control when logs are emitted. The package provides an interface to create custom rules (IRule) and a mechanism for callback (IExecutionHook) to perform some after-rule actions.

Predefined Rules

BatchSizeRule

This rule triggers batch emitting when a specific batch size is reached.

OncePerTimeRule

This rule ensures that the logs are emitted in batches at regular intervals.

Creating Custom Rules

You can create a class that implements the IRule interface to implement a custom rule. Here's an example of a custom rule:

public class CustomRule : IRule
{
    public bool IsSatisfied(LogEvent logEvent)
    {
        // Your custom logic
    }
    
    // Additional members
}

Execution Hooks

Execution hooks can be implemented using the IExecutionHook interface. These hooks provide a callback mechanism, such as resetting the state of rules on the batches emitting.

Example:

public class CustomRule : IRule, IExecutionHook
{
    // IRule interface implementation

    public void OnBatchEmitting()
    {
        // Your custom logic
    }
}

Configuration

To configure execution rules, users must use the BatchEmittingRulesConfiguration. More details about BatchEmittingRulesConfiguration can be found here. Note that these rules work as OR conditions, and now this behavior a can't be configured. If you think this must be configurable, please create an issue (feature request), and I will work on it in the next release.

Example

Here is an example demonstrating how to implement a custom rule with an execution hook and register it through the configuration:

config.BatchEmittingRulesConfiguration = new BatchEmittingRulesConfiguration()
{
    RuleCheckPeriod = TimeSpan.FromSeconds(30), // Check batch emitting rules each 30 seconds
    BatchProcessingRules = new List<IRule>()
    {
        new BatchSizeRule(config.LogsAccessor, 5), // emit batch when logs queue length
                                                  // equals or greater than 5
        new OncePerTimeRule(TimeSpan.FromMinutes(5)) // emit batch each 5 minutes
    }.ToImmutableList()
};

If you need more help and information, please refer to the official GitHub repository of the X.Serilog.Sinks.Telegram package.

Clone this wiki locally