Skip to content
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

Avoid string.Split in LoggerRuleSelector.IsBetter #44753

Merged
merged 1 commit into from
Nov 18, 2020
Merged
Changes from all commits
Commits
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 @@ -7,8 +7,6 @@ namespace Microsoft.Extensions.Logging
{
internal class LoggerRuleSelector
{
private static readonly char[] WildcardChar = { '*' };

public void Select(LoggerFilterOptions options, Type providerType, string category, out LogLevel? minLevel, out Func<string, string, LogLevel, bool> filter)
{
filter = null;
Expand Down Expand Up @@ -40,7 +38,6 @@ public void Select(LoggerFilterOptions options, Type providerType, string catego
}
}


private static bool IsBetter(LoggerFilterRule rule, LoggerFilterRule current, string logger, string category)
{
// Skip rules with inapplicable type or category
Expand All @@ -49,19 +46,32 @@ private static bool IsBetter(LoggerFilterRule rule, LoggerFilterRule current, st
return false;
}

if (rule.CategoryName != null)
string categoryName = rule.CategoryName;
if (categoryName != null)
{
string[] categoryParts = rule.CategoryName.Split(WildcardChar);
if (categoryParts.Length > 2)
const char WildcardChar = '*';

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

string prefix = categoryParts[0];
string suffix = categoryParts.Length > 1 ? categoryParts[1] : string.Empty;
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.StartsWith(prefix, StringComparison.OrdinalIgnoreCase) ||
!category.EndsWith(suffix, StringComparison.OrdinalIgnoreCase))
if (!category.AsSpan().StartsWith(prefix, StringComparison.OrdinalIgnoreCase) ||
!category.AsSpan().EndsWith(suffix, StringComparison.OrdinalIgnoreCase))
{
return false;
}
Expand Down