Skip to content

Commit

Permalink
MicrosoftConsoleLayoutRenderer - Skip string-allocation for EventId w…
Browse files Browse the repository at this point in the history
…hen possible on platform (#572)
  • Loading branch information
snakefoot committed Feb 8, 2022
1 parent 45ec960 commit fd024c9
Showing 1 changed file with 16 additions and 17 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -50,8 +50,7 @@ protected override void Append(StringBuilder builder, LogEventInfo logEvent)
builder.Append(": ");
builder.Append(logEvent.LoggerName);
builder.Append('[');
var eventId = LookupEventId(logEvent);
builder.Append(eventId);
AppendEventId(LookupEventId(logEvent), builder);
builder.Append(']');
builder.Append(System.Environment.NewLine);
builder.Append(" ");
Expand All @@ -63,35 +62,35 @@ protected override void Append(StringBuilder builder, LogEventInfo logEvent)
}
}

private static string LookupEventId(LogEventInfo logEvent)
private static void AppendEventId(int eventId, StringBuilder builder)
{
if (eventId == 0)
builder.Append('0');
else if (eventId > 0 && eventId < EventIdMapper.Length)
builder.Append(EventIdMapper[eventId]);
else
builder.Append(eventId); // .NET5 (and newer) can append integer without string-allocation (using span)
}

private static int LookupEventId(LogEventInfo logEvent)
{
if (logEvent.HasProperties)
{
if (logEvent.Properties.TryGetValue(nameof(EventIdCaptureType.EventId), out var eventObject))
{
if (eventObject is int eventId)
return ConvertEventId(eventId);
return eventId;
else if (eventObject is Microsoft.Extensions.Logging.EventId eventIdStruct)
return ConvertEventId(eventIdStruct.Id);
return eventIdStruct.Id;
}

if (logEvent.Properties.TryGetValue(nameof(EventIdCaptureType.EventId_Id), out var eventid) && eventid is int)
{
return ConvertEventId((int)eventid);
return (int)eventid;
}
}

return "0";
}

private static string ConvertEventId(int eventId)
{
if (eventId == 0)
return "0";
else if (eventId > 0 && eventId < EventIdMapper.Length)
return EventIdMapper[eventId];
else
return eventId.ToString(System.Globalization.CultureInfo.InvariantCulture);
return 0;
}

private static string ConvertLogLevel(LogLevel logLevel)
Expand Down

0 comments on commit fd024c9

Please sign in to comment.