Skip to content

Use IReadOnlyList type-matching to avoid enumerator allocation. #279

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

Open
wants to merge 1 commit into
base: dev
Choose a base branch
from
Open
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
86 changes: 55 additions & 31 deletions src/Serilog.Extensions.Logging/Extensions/Logging/SerilogLogger.cs
Original file line number Diff line number Diff line change
Expand Up @@ -91,43 +91,27 @@ LogEvent PrepareWrite<TState>(LogEventLevel level, EventId eventId, TState state

var properties = new Dictionary<string, LogEventPropertyValue>();

if (state is IEnumerable<KeyValuePair<string, object?>> structure)
// Optimization: MEL state object type represents either LogValues or FormattedLogValues
// These types implement IReadOnlyList, which be used to avoid enumerator obj allocation.
if (state is IReadOnlyList<KeyValuePair<string, object?>> propertiesList)
{
foreach (var property in structure)
var length = propertiesList.Count;

for (var i = 0; i < length; i++)
{
if (property is { Key: SerilogLoggerProvider.OriginalFormatPropertyName, Value: string value })
{
messageTemplate = value;
}
else if (property.Key.StartsWith('@'))
{
if (_logger.BindProperty(GetKeyWithoutFirstSymbol(DestructureDictionary, property.Key), property.Value, true, out var destructured))
properties[destructured.Name] = destructured.Value;
}
else if (property.Key.StartsWith('$'))
{
if (_logger.BindProperty(GetKeyWithoutFirstSymbol(StringifyDictionary, property.Key), property.Value?.ToString(), true, out var stringified))
properties[stringified.Name] = stringified.Value;
}
else
{
// Simple micro-optimization for the most common and reliably scalar values; could go further here.
if (property.Value is null or string or int or long && LogEventProperty.IsValidName(property.Key))
properties[property.Key] = new ScalarValue(property.Value);
else if (_logger.BindProperty(property.Key, property.Value, false, out var bound))
properties[bound.Name] = bound.Value;
}
ProcessStateProperty(propertiesList[i]);
}

var stateType = state.GetType();
var stateTypeInfo = stateType.GetTypeInfo();
// Imperfect, but at least eliminates `1 names
if (messageTemplate == null && !stateTypeInfo.IsGenericType)
TrySetMessageTemplateFromState();
}
else if (state is IEnumerable<KeyValuePair<string, object?>> propertiesEnumerable)
{
foreach (var property in propertiesEnumerable)
{
messageTemplate = "{" + stateType.Name + ":l}";
if (_logger.BindProperty(stateType.Name, AsLoggableValue(state, formatter), false, out var stateTypeProperty))
properties[stateTypeProperty.Name] = stateTypeProperty.Value;
ProcessStateProperty(property);
}

TrySetMessageTemplateFromState();
}

if (messageTemplate == null)
Expand Down Expand Up @@ -163,6 +147,46 @@ LogEvent PrepareWrite<TState>(LogEventLevel level, EventId eventId, TState state

var parsedTemplate = messageTemplate != null ? MessageTemplateParser.Parse(messageTemplate) : MessageTemplate.Empty;
return LogEvent.UnstableAssembleFromParts(DateTimeOffset.Now, level, exception, parsedTemplate, properties, traceId, spanId);

void ProcessStateProperty(KeyValuePair<string, object?> property)
{
if (property is { Key: SerilogLoggerProvider.OriginalFormatPropertyName, Value: string value })
{
messageTemplate = value;
}
else if (property.Key.StartsWith('@'))
{
if (this._logger.BindProperty(GetKeyWithoutFirstSymbol(DestructureDictionary, property.Key), property.Value, true, out var destructured))
properties[destructured.Name] = destructured.Value;
}
else if (property.Key.StartsWith('$'))
{
if (this._logger.BindProperty(GetKeyWithoutFirstSymbol(StringifyDictionary, property.Key), property.Value?.ToString(), true, out var stringified))
properties[stringified.Name] = stringified.Value;
}
else
{
// Simple micro-optimization for the most common and reliably scalar values; could go further here.
if (property.Value is null or string or int or long && LogEventProperty.IsValidName(property.Key))
properties[property.Key] = new ScalarValue(property.Value);
else if (this._logger.BindProperty(property.Key, property.Value, false, out var bound))
properties[bound.Name] = bound.Value;
}
}

void TrySetMessageTemplateFromState()
{
// Imperfect, but at least eliminates `1 names
var stateType = state.GetType();
var stateTypeInfo = stateType.GetTypeInfo();
// Imperfect, but at least eliminates `1 names
if (messageTemplate == null && !stateTypeInfo.IsGenericType)
{
messageTemplate = "{" + stateType.Name + ":l}";
if (_logger.BindProperty(stateType.Name, AsLoggableValue(state, formatter), false, out var stateTypeProperty))
properties[stateTypeProperty.Name] = stateTypeProperty.Value;
}
}
}

static object? AsLoggableValue<TState>(TState state, Func<TState, Exception?, string>? formatter)
Expand Down