Skip to content

Add logging sampling #5574

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 67 commits into from
Feb 27, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
67 commits
Select commit Hold shift + click to select a range
1280d1b
initial proposal
Jun 5, 2024
f8b502c
update
Jul 3, 2024
ed7e0db
rebase
evgenyfedorov2 Sep 12, 2024
e15139d
use .net 9
evgenyfedorov2 Sep 30, 2024
12fd4b4
bufferin - initial
evgenyfedorov2 Oct 7, 2024
9fa8403
Remove junk
evgenyfedorov2 Oct 7, 2024
2ff5f78
buffer - renames
evgenyfedorov2 Oct 9, 2024
0cf2c50
.
evgenyfedorov2 Oct 9, 2024
6f8265e
.
evgenyfedorov2 Oct 9, 2024
cdb2c82
Sampling WIP with Global and HttpRequest samplers
evgenyfedorov2 Oct 14, 2024
cb1de9d
sampling
evgenyfedorov2 Oct 14, 2024
c4596a3
cosmetic
evgenyfedorov2 Oct 14, 2024
5e92d14
Prepare to update API proposal
evgenyfedorov2 Oct 15, 2024
8f760b1
.
evgenyfedorov2 Oct 15, 2024
57f902b
state at 23_10_2024 after updating Github proposal
evgenyfedorov2 Oct 23, 2024
610647c
Return Global and Http Request buffering options
evgenyfedorov2 Oct 24, 2024
3be3850
polish sampling
evgenyfedorov2 Oct 24, 2024
8ce40c1
add alwaysOnSampler
evgenyfedorov2 Oct 24, 2024
d288300
update namespaces
evgenyfedorov2 Oct 24, 2024
e120145
abstractions test
evgenyfedorov2 Oct 24, 2024
b443094
add some tests
evgenyfedorov2 Oct 25, 2024
b41fcdf
remove buffering
evgenyfedorov2 Oct 25, 2024
a5e1440
merge
evgenyfedorov2 Oct 25, 2024
cbd2a15
update tests
evgenyfedorov2 Oct 25, 2024
5580cff
remove sample app
evgenyfedorov2 Oct 25, 2024
07a2860
cosmetic changes
evgenyfedorov2 Oct 25, 2024
9ac7cab
update tests
evgenyfedorov2 Oct 25, 2024
0df498f
validate supplied probability
evgenyfedorov2 Oct 25, 2024
7b9479d
Fix warnings
evgenyfedorov2 Oct 25, 2024
4007ce1
Merge branch 'main' into evgenyfedorov2/log_sampling
evgenyfedorov2 Oct 26, 2024
473bfca
more tests
evgenyfedorov2 Oct 26, 2024
b140e68
Address PR comments
evgenyfedorov2 Oct 30, 2024
32b5adc
Address PR comments
evgenyfedorov2 Oct 31, 2024
ebd4795
wip
evgenyfedorov2 Nov 4, 2024
901bc22
add config support to Ratio based Sampler
evgenyfedorov2 Nov 6, 2024
e33863e
fix warnings
evgenyfedorov2 Nov 6, 2024
d43f891
Merge branch 'main' into evgenyfedorov2/log_sampling
evgenyfedorov2 Nov 6, 2024
0adbfc7
PR comments
evgenyfedorov2 Nov 7, 2024
e938600
PR Comments
evgenyfedorov2 Nov 7, 2024
d49c1f1
Merge branch 'main' into evgenyfedorov2/log_sampling
evgenyfedorov2 Nov 12, 2024
1606acb
Merge branch 'main' into evgenyfedorov2/log_sampling
evgenyfedorov2 Dec 3, 2024
a831d20
PR Comments
evgenyfedorov2 Dec 3, 2024
9263b04
PR Comments
evgenyfedorov2 Dec 3, 2024
cf30f0e
Add more tests
evgenyfedorov2 Dec 3, 2024
57f7080
Add log message state to SamplingParameters
evgenyfedorov2 Dec 3, 2024
10ad269
More tests
evgenyfedorov2 Dec 3, 2024
a8bdc6e
Use LogEntry and remove func based sampler
evgenyfedorov2 Feb 12, 2025
08a40d2
Rename Probability to Probabilistic
evgenyfedorov2 Feb 12, 2025
997deb2
ProbabilisticSamplerOptions to use IList
evgenyfedorov2 Feb 12, 2025
8a8ddc1
Add event name
evgenyfedorov2 Feb 12, 2025
3a240fb
Add an overload with Action delegate
evgenyfedorov2 Feb 12, 2025
f8e0bc1
Merge branch 'main' into evgenyfedorov2/log_sampling
evgenyfedorov2 Feb 12, 2025
26db353
Rename Category to CategoryName to better match log filtering API
evgenyfedorov2 Feb 14, 2025
3b320aa
Merge branch 'evgenyfedorov2/log_sampling' of https://github.com/evge…
evgenyfedorov2 Feb 14, 2025
49459b6
Update
evgenyfedorov2 Feb 14, 2025
cfd544b
Minor changes
evgenyfedorov2 Feb 21, 2025
017a89c
Merge branch 'main' into evgenyfedorov2/log_sampling
evgenyfedorov2 Feb 21, 2025
654d22f
Rename Probabilistic to RandomProbabilistic
evgenyfedorov2 Feb 21, 2025
64a348e
more tests
evgenyfedorov2 Feb 21, 2025
cb4de8b
Add options validation
evgenyfedorov2 Feb 24, 2025
97c26cc
Minor optimization
evgenyfedorov2 Feb 24, 2025
eb3b660
Merge branch 'main' into evgenyfedorov2/log_sampling
evgenyfedorov2 Feb 25, 2025
c05e86e
Merge branch 'main' into evgenyfedorov2/log_sampling
evgenyfedorov2 Feb 26, 2025
0b1f973
Cosmetic update
evgenyfedorov2 Feb 26, 2025
8868c9b
Add rule caching
evgenyfedorov2 Feb 26, 2025
e7c7fe0
PR comments
evgenyfedorov2 Feb 27, 2025
1e678e5
Merge branch 'main' into evgenyfedorov2/log_sampling
evgenyfedorov2 Feb 27, 2025
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,6 @@
<InjectSharedPools>false</InjectSharedPools>
<InjectSharedBufferWriterPool>true</InjectSharedBufferWriterPool>
<InjectSharedNumericExtensions>false</InjectSharedNumericExtensions>
<InjectSharedDiagnosticIds>true</InjectSharedDiagnosticIds>
<InjectExperimentalAttributeOnLegacy>true</InjectExperimentalAttributeOnLegacy>
</PropertyGroup>

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,6 @@
<UseMetricsReportsGenerator>true</UseMetricsReportsGenerator>
<InjectGetOrAddOnLegacy>false</InjectGetOrAddOnLegacy>
<InjectTaskWaitAsyncOnLegacy>true</InjectTaskWaitAsyncOnLegacy>
<InjectSharedDiagnosticIds>true</InjectSharedDiagnosticIds>
<InjectExperimentalAttributeOnLegacy>true</InjectExperimentalAttributeOnLegacy>
<InjectTrimAttributesOnLegacy>false</InjectTrimAttributesOnLegacy>
<InjectSharedDebugger>true</InjectSharedDebugger>
<InjectSharedDataValidation>false</InjectSharedDataValidation>
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

using System.Diagnostics.CodeAnalysis;
using Microsoft.Extensions.Logging.Abstractions;
using Microsoft.Shared.DiagnosticIds;

namespace Microsoft.Extensions.Logging;

/// <summary>
/// Controls the number of samples of log records collected and sent to the backend.
/// </summary>
#pragma warning disable S1694 // An abstract class should have both abstract and concrete methods
[Experimental(diagnosticId: DiagnosticIds.Experiments.Telemetry, UrlFormat = DiagnosticIds.UrlFormat)]
public abstract class LoggingSampler
#pragma warning restore S1694 // An abstract class should have both abstract and concrete methods
{
/// <summary>
/// Makes a sampling decision for the provided <paramref name="logEntry"/>.
/// </summary>
/// <param name="logEntry">The log entry used to make the sampling decision for.</param>
/// <typeparam name="TState">The type of the log entry state.</typeparam>
/// <returns><see langword="true" /> if the log record should be sampled; otherwise, <see langword="false" />.</returns>
public abstract bool ShouldSample<TState>(in LogEntry<TState> logEntry);
}
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
using System;
using System.Collections.Generic;
using System.Diagnostics;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Abstractions;
using Microsoft.Shared.Pools;

namespace Microsoft.Extensions.Logging;
Expand All @@ -15,7 +15,7 @@ namespace Microsoft.Extensions.Logging;
// redactor code calls recursively back into the logger. Don't do that.
//
// NOTE: Unlike the original logger in dotnet/runtime, this logger eats exceptions thrown from invoked loggers, enrichers,
// and redactors, rather than forwarding the exceptions to the caller. The fact an exception occured is recorded in
// and redactors, rather than forwarding the exceptions to the caller. The fact an exception occurred is recorded in
// the event log instead. The idea is that failures in the telemetry stack should not lead to failures in the
// application. It's better to keep running with missing telemetry rather than crashing the process completely.

Expand Down Expand Up @@ -49,7 +49,7 @@ public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Except
}
}

LegacyPath<TState>(logLevel, eventId, state, exception, formatter);
LegacyPath(logLevel, eventId, state, exception, formatter);
}

public IDisposable? BeginScope<TState>(TState state)
Expand Down Expand Up @@ -261,16 +261,33 @@ private void ModernPath(LogLevel logLevel, EventId eventId, LoggerMessageState m
RecordException(exception, joiner.EnrichmentTagCollector, config);
}

bool? samplingDecision = null;
for (int i = 0; i < loggers.Length; i++)
{
ref readonly MessageLogger loggerInfo = ref loggers[i];
if (loggerInfo.IsNotFilteredOut(logLevel))
{
if (samplingDecision is null && config.Sampler is not null)
{
var logEntry = new LogEntry<ModernTagJoiner>(logLevel, loggerInfo.Category, eventId, joiner, exception, static (s, e) =>
{
Func<LoggerMessageState, Exception?, string> fmt = s.Formatter!;
return fmt(s.State!, e);
});
samplingDecision = config.Sampler.ShouldSample(in logEntry);
}

if (samplingDecision is false)
{
// the record was not selected for being sampled in, so we drop it.
break;
}

try
{
loggerInfo.LoggerLog(logLevel, eventId, joiner, exception, static (s, e) =>
{
var fmt = s.Formatter!;
Func<LoggerMessageState, Exception?, string>? fmt = s.Formatter!;
return fmt(s.State!, e);
});
}
Expand Down Expand Up @@ -345,11 +362,28 @@ private void LegacyPath<TState>(LogLevel logLevel, EventId eventId, TState state
RecordException(exception, joiner.EnrichmentTagCollector, config);
}

bool? samplingDecision = null;
for (int i = 0; i < loggers.Length; i++)
{
ref readonly MessageLogger loggerInfo = ref loggers[i];
if (loggerInfo.IsNotFilteredOut(logLevel))
{
if (samplingDecision is null && config.Sampler is not null)
{
var logEntry = new LogEntry<LegacyTagJoiner>(logLevel, loggerInfo.Category, eventId, joiner, exception, static (s, e) =>
{
var fmt = (Func<TState, Exception?, string>)s.Formatter!;
return fmt((TState)s.State!, e);
});
samplingDecision = config.Sampler.ShouldSample(in logEntry);
}

if (samplingDecision is false)
{
// the record was not selected for being sampled in, so we drop it.
break;
}

try
{
loggerInfo.Logger.Log(logLevel, eventId, joiner, exception, static (s, e) =>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ internal sealed class ExtendedLoggerFactory : ILoggerFactory
private readonly IDisposable? _enrichmentOptionsChangeTokenRegistration;
private readonly IDisposable? _redactionOptionsChangeTokenRegistration;
private readonly Action<IEnrichmentTagCollector>[] _enrichers;
private readonly LoggingSampler? _sampler;
private readonly KeyValuePair<string, object?>[] _staticTags;
private readonly Func<DataClassificationSet, Redactor> _redactorProvider;
private volatile bool _disposed;
Expand All @@ -35,6 +36,7 @@ public ExtendedLoggerFactory(
IEnumerable<ILogEnricher> enrichers,
IEnumerable<IStaticLogEnricher> staticEnrichers,
IOptionsMonitor<LoggerFilterOptions> filterOptions,
LoggingSampler? sampler = null,
IOptions<LoggerFactoryOptions>? factoryOptions = null,
IExternalScopeProvider? scopeProvider = null,
IOptionsMonitor<LoggerEnrichmentOptions>? enrichmentOptions = null,
Expand All @@ -43,6 +45,7 @@ public ExtendedLoggerFactory(
#pragma warning restore S107 // Methods should not have too many parameters
{
_scopeProvider = scopeProvider;
_sampler = sampler;

_factoryOptions = factoryOptions == null || factoryOptions.Value == null ? new LoggerFactoryOptions() : factoryOptions.Value;

Expand Down Expand Up @@ -284,6 +287,7 @@ private LoggerConfig ComputeConfig(LoggerEnrichmentOptions? enrichmentOptions, L

return new(_staticTags,
_enrichers,
_sampler,
enrichmentOptions.CaptureStackTraces,
enrichmentOptions.UseFileInfoForStackTraces,
enrichmentOptions.IncludeExceptionMessage,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ namespace Microsoft.Extensions.Logging
{
internal readonly struct MessageLogger
{
public MessageLogger(ILogger logger, string? category, string? providerTypeFullName, LogLevel? minLevel, Func<string?, string?, LogLevel, bool>? filter)
public MessageLogger(ILogger logger, string category, string? providerTypeFullName, LogLevel? minLevel, Func<string?, string?, LogLevel, bool>? filter)
{
Logger = logger;
Category = category;
Expand All @@ -36,7 +36,7 @@ public MessageLogger(ILogger logger, string? category, string? providerTypeFullN

public ILogger Logger { get; }

public string? Category { get; }
public string Category { get; }

private string? ProviderTypeFullName { get; }

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ internal sealed class LoggerConfig
public LoggerConfig(
KeyValuePair<string, object?>[] staticTags,
Action<IEnrichmentTagCollector>[] enrichers,
LoggingSampler? sampler,
bool captureStackTraces,
bool useFileInfoForStackTraces,
bool includeExceptionMessage,
Expand All @@ -25,6 +26,7 @@ public LoggerConfig(
#pragma warning restore S107 // Methods should not have too many parameters
StaticTags = staticTags;
Enrichers = enrichers;
Sampler = sampler;
CaptureStackTraces = captureStackTraces;
UseFileInfoForStackTraces = useFileInfoForStackTraces;
MaxStackTraceLength = maxStackTraceLength;
Expand All @@ -35,6 +37,7 @@ public LoggerConfig(

public KeyValuePair<string, object?>[] StaticTags { get; }
public Action<IEnrichmentTagCollector>[] Enrichers { get; }
public LoggingSampler? Sampler { get; }
public bool CaptureStackTraces { get; }
public bool UseFileInfoForStackTraces { get; }
public bool IncludeExceptionMessage { get; }
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@

<PropertyGroup>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
<InjectExperimentalAttributeOnLegacy>true</InjectExperimentalAttributeOnLegacy>
<InjectSharedDiagnosticIds>true</InjectSharedDiagnosticIds>
<InjectSharedText>true</InjectSharedText>
<InjectSharedDataValidation>true</InjectSharedDataValidation>
<InjectSharedNumericExtensions>true</InjectSharedNumericExtensions>
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

using Microsoft.Extensions.Logging;

namespace Microsoft.Extensions.Diagnostics.Sampling;

/// <summary>
/// Represents a rule used for filtering log messages for purposes of log sampling and buffering.
/// </summary>
internal interface ILogSamplingFilterRule
{
/// <summary>
/// Gets the logger category this rule applies to.
/// </summary>
string? CategoryName { get; }

/// <summary>
/// Gets the maximum <see cref="LogLevel"/> of messages.
/// </summary>
LogLevel? LogLevel { get; }

/// <summary>
/// Gets the event ID this rule applies to.
/// </summary>
int? EventId { get; }

/// <summary>
/// Gets the name of the event this rule applies to.
/// </summary>
string? EventName { get; }
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,135 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

#pragma warning disable CA1307 // Specify StringComparison for clarity
#pragma warning disable S1659 // Multiple variables should not be declared on the same line
#pragma warning disable S2302 // "nameof" should be used

using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using Microsoft.Extensions.Diagnostics.Sampling;
using Microsoft.Extensions.Logging;

namespace Microsoft.Extensions.Diagnostics.Sampling;

internal sealed class LogSamplingRuleSelector<T>
where T : class, ILogSamplingFilterRule
{
private readonly ConcurrentDictionary<(string, LogLevel, EventId), T?> _ruleCache = new();

public void InvalidateCache()
{
_ruleCache.Clear();
}

public T? Select(IList<T> rules, string category, LogLevel logLevel, EventId eventId)
{
return _ruleCache.GetOrAdd((category, logLevel, eventId), _ =>
{
// Filter rule selection:
// 0. Ignore rules whose LogLevel is defined but lower than the requested logLevel
// 1. Ignore rules whose EventId is defined but different from the requested eventId
// 2. For category filtering, handle optional wildcards (only one '*' allowed) and match the prefix/suffix ignoring case
// 3. Out of the matched set, pick the rule with the longest matching category
// 4. If no rules match by category, accept rules without a category
// 5. If exactly one rule remains, use it; if multiple remain, select the last in the list
T? current = null;
foreach (T rule in rules)
{
if (IsBetter(rule, current, category, logLevel, eventId))
{
current = rule;
}
}

return current;
});
}

private static bool IsBetter(T rule, T? current, string category, LogLevel logLevel, EventId eventId)
{
// Skip rules with inapplicable log level
if (rule.LogLevel is not null && rule.LogLevel < logLevel)
{
return false;
}

// Skip rules with inapplicable event id
if (rule.EventId is not null && rule.EventId != eventId)
{
return false;
}

// Skip rules with inapplicable category
string? categoryName = rule.CategoryName;
if (categoryName is not null)
{
const char WildcardChar = '*';

int wildcardIndex = categoryName.IndexOf(WildcardChar);
if (wildcardIndex >= 0 &&
categoryName.IndexOf(WildcardChar, wildcardIndex + 1) >= 0)
{
throw new InvalidOperationException("Only one wildcard character is allowed in category name.");
}

ReadOnlySpan<char> prefix, suffix;
if (wildcardIndex == -1)
{
prefix = categoryName.AsSpan();
suffix = default;
}
else
{
prefix = categoryName.AsSpan(0, wildcardIndex);
suffix = categoryName.AsSpan(wildcardIndex + 1);
}

if (!category.AsSpan().StartsWith(prefix, StringComparison.OrdinalIgnoreCase) ||
!category.AsSpan().EndsWith(suffix, StringComparison.OrdinalIgnoreCase))
{
return false;
}
}

// Decide whose category is better - rule vs current
if (current?.CategoryName is not null)
{
if (rule.CategoryName is null)
{
return false;
}

if (current.CategoryName.Length > rule.CategoryName.Length)
{
return false;
}
}

// Decide whose log level is better - rule vs current
if (current?.LogLevel is not null)
{
if (rule.LogLevel is null)
{
return false;
}

if (current.LogLevel < rule.LogLevel)
{
return false;
}
}

// Decide whose event id is better - rule vs current
if (rule.EventId is null)
{
if (current?.EventId is not null)
{
return false;
}
}

return true;
}
}
Loading
Loading