Skip to content

Commit d5af5fc

Browse files
committed
MicrosoftConsoleLayoutRenderer - Skip string-allocation for EventId when possible on platform (#572)
1 parent 48e4c77 commit d5af5fc

1 file changed

Lines changed: 31 additions & 19 deletions

File tree

src/NLog.Extensions.Logging/LayoutRenderers/MicrosoftConsoleLayoutRenderer.cs

Lines changed: 31 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -22,21 +22,9 @@ protected override void Append(StringBuilder builder, LogEventInfo logEvent)
2222
builder.Append(microsoftLogLevel);
2323
builder.Append(": ");
2424
builder.Append(logEvent.LoggerName);
25-
builder.Append("[");
26-
int eventId = 0;
27-
if (logEvent.HasProperties && logEvent.Properties.TryGetValue("EventId_Id", out var eventIdValue))
28-
{
29-
if (eventIdValue is int)
30-
eventId = (int)eventIdValue;
31-
else if (!int.TryParse(eventIdValue?.ToString() ?? string.Empty, out eventId))
32-
eventId = 0;
33-
}
34-
else
35-
{
36-
eventId = 0;
37-
}
38-
builder.Append(ConvertEventId(eventId));
39-
builder.Append("]");
25+
builder.Append('[');
26+
AppendEventId(LookupEventId(logEvent), builder);
27+
builder.Append(']');
4028
builder.Append(System.Environment.NewLine);
4129
builder.Append(" ");
4230
builder.Append(logEvent.FormattedMessage);
@@ -47,14 +35,38 @@ protected override void Append(StringBuilder builder, LogEventInfo logEvent)
4735
}
4836
}
4937

50-
static string ConvertEventId(int eventId)
38+
private static void AppendEventId(int eventId, StringBuilder builder)
5139
{
5240
if (eventId == 0)
53-
return "0";
41+
builder.Append('0');
5442
else if (eventId > 0 && eventId < EventIdMapper.Length)
55-
return EventIdMapper[eventId];
43+
builder.Append(EventIdMapper[eventId]);
5644
else
57-
return eventId.ToString();
45+
builder.Append(eventId); // .NET5 (and newer) can append integer without string-allocation (using span)
46+
}
47+
48+
private static int LookupEventId(LogEventInfo logEvent)
49+
{
50+
if (logEvent.HasProperties)
51+
{
52+
if (logEvent.Properties.TryGetValue("EventId_Id", out var eventObject))
53+
{
54+
if (eventObject is int eventId)
55+
return eventId;
56+
else if (eventObject is Microsoft.Extensions.Logging.EventId eventIdStruct)
57+
return eventIdStruct.Id;
58+
}
59+
60+
if (logEvent.Properties.TryGetValue("EventId", out var eventid))
61+
{
62+
if (eventObject is int eventId)
63+
return eventId;
64+
else if (eventObject is Microsoft.Extensions.Logging.EventId eventIdStruct)
65+
return eventIdStruct.Id;
66+
}
67+
}
68+
69+
return 0;
5870
}
5971

6072
string ConvertLogLevel(LogLevel logLevel)

0 commit comments

Comments
 (0)