Files
EonaCat.LogStack/EonaCat.LogStack/EonaCatLoggerCore/Policies/SamplingPolicy.cs
T
2026-04-06 08:15:54 +02:00

39 lines
1.2 KiB
C#

using EonaCat.LogStack.Core;
using System;
using System.Runtime.CompilerServices;
using System.Threading;
namespace EonaCat.LogStack.EonaCatLogStackCore.Policies
{
// This file is part of the EonaCat project(s) which is released under the Apache License.
// See the LICENSE file or go to https://EonaCat.com/License for full license details.
/// <summary>Log only 1-in-N events, optionally filtered by a predicate.</summary>
public sealed class SamplingPolicy
{
private long _counter;
/// <summary>Keep 1 out of every <see cref="Rate"/> events.</summary>
public int Rate { get; set; }
/// <summary>Optional predicate. Null = apply to all events.</summary>
public Func<LogEvent, bool> Predicate { get; set; }
public SamplingPolicy()
{
Rate = 10;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public bool ShouldLog(LogEvent e)
{
if (Predicate != null && !Predicate(e))
{
// predicate not matched → always log
return true;
}
return Interlocked.Increment(ref _counter) % Rate == 0;
}
}
}