79418614

Date: 2025-02-06 16:17:13
Score: 0.5
Natty:
Report link

Ok, I fixed this myself with a really really ugly hack.

My DuplicateFilterSink class now looks like this:

public class DuplicateFilterSink : ILogEventSink
{
    private readonly ILogEventSink _innerSink;
    private LogEvent? _prevLogEvent;
    private int _duplicateCount = 0;

    public DuplicateFilterSink(ILogEventSink innerSink)
    {
        _innerSink = innerSink;
    }

    public void Emit(LogEvent logEvent)
    {
        // Check if the message is the same as the previous one
        if (_prevLogEvent != null && logEvent.MessageTemplate.Text == _prevLogEvent.MessageTemplate.Text)
        {
            _duplicateCount++;
        }
        else
        {
            // If the message has changed, log the previous duplicate count
            if (_duplicateCount > 0 && !logEvent.MessageTemplate.Text.StartsWith("  * The previous message occurred"))
            {
                string dupmsg = $"  * The previous message occurred {_duplicateCount} times";

                Log.Information(dupmsg, _duplicateCount);

                _duplicateCount = 0;
            }

            // Log the new message
            _innerSink.Emit(logEvent);
            _prevLogEvent = logEvent;
        }
    }
}

Since I have not figured out a way to create a valid MessageTemplate with a valid MessageTemplateToken, I tried using the Log.Information() line, but that created an infinite recursion loop because the Log method kept calling the Sink which called the Log method which called the... well, you get it.

I combated this problem by adding the "&& !logEvent.MessageTemplate.Text.StartsWith(..." condition to the if statement so that the second time through it would not Log method again.

This works, but is horribly Kludgy. I will be greatful if anyone can solve my original problem in a "best-practices" way.

Reasons:
  • Whitelisted phrase (-2): I fixed
  • RegEx Blacklisted phrase (2): I will be greatful
  • RegEx Blacklisted phrase (0.5): anyone can solve
  • Long answer (-1):
  • Has code block (-0.5):
  • Self-answer (0.5):
  • Low reputation (1):
Posted by: Dogulas