Skip to content

Batch Emitting Rules

Vladyslav Bardin edited this page Aug 11, 2023 · 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, providing examples for creating custom rules and including details about the predefined rules.

Introduction

The batch emitting rules allow users to control when logs are emitted in batches. The package provides an interface to create custom rules (IRule) and a mechanism for callback (IExecutionHook).

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 rules' state on batch 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.

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

var logger = new LoggerConfiguration()
    .WriteTo.Telegram(config =>
    {
        config.Token = "0000000000:0000000000000000000-0000000-0000000";
        config.ChatId = "-000000000000";
        config.BatchEmittingRulesConfiguration = new BatchEmittingRulesConfiguration
        {
            RuleCheckPeriod = TimeSpan.FromSeconds(5),
            BatchProcessingRules = new IRule[]
            {
                new BatchSizeRule(config.LogsAccessor, batchSize: 10),
                new OncePerTimeRule(TimeSpan.FromSeconds(30))
            }.ToImmutableList()
        };
    }, null!, LogEventLevel.Information)
    .CreateLogger();

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