Skip to content

Commit 46dfbf4

Browse files
committed
Encapsulate item management logic in ScopeCollector.
1 parent 8fb1e0f commit 46dfbf4

File tree

1 file changed

+15
-10
lines changed

1 file changed

+15
-10
lines changed

src/Serilog.Extensions.Logging/Extensions/Logging/SerilogLoggerProvider.cs

Lines changed: 15 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -103,7 +103,7 @@ public void Enrich(LogEvent logEvent, ILogEventPropertyFactory propertyFactory)
103103
}
104104
}
105105

106-
scopeCollector.ScopeItems?.Reverse();
106+
scopeCollector.ReverseItems();
107107

108108
_externalScopeProvider?.ForEachScope(static (state, parameters) =>
109109
{
@@ -120,12 +120,10 @@ public void Enrich(LogEvent logEvent, ILogEventPropertyFactory propertyFactory)
120120
}
121121
}, (ScopeCollector: scopeCollector, PropertyFactory: propertyFactory, LogEvent: logEvent));
122122

123-
if (scopeCollector.ScopeItems != null)
123+
if (scopeCollector.Complete() is { } items)
124124
{
125-
logEvent.AddPropertyIfAbsent(new LogEventProperty(ScopePropertyName, new SequenceValue(scopeCollector.ScopeItems)));
125+
logEvent.AddPropertyIfAbsent(new LogEventProperty(ScopePropertyName, new SequenceValue(items)));
126126
}
127-
128-
scopeCollector.Clear();
129127
}
130128

131129
/// <inheritdoc />
@@ -159,16 +157,23 @@ public ValueTask DisposeAsync()
159157
/// <summary>
160158
/// A wrapper around a list to allow lazy initialization when iterating through scopes.
161159
/// </summary>
162-
private sealed class ScopeCollector
160+
sealed class ScopeCollector
163161
{
164-
public List<LogEventPropertyValue>? ScopeItems { get; private set; }
162+
List<LogEventPropertyValue>? _scopeItems;
165163

166164
public void AddItem(LogEventPropertyValue scopeItem)
167165
{
168-
ScopeItems ??= [];
169-
ScopeItems.Add(scopeItem);
166+
_scopeItems ??= [];
167+
_scopeItems.Add(scopeItem);
170168
}
171169

172-
public void Clear() => this.ScopeItems = null;
170+
public void ReverseItems() => _scopeItems?.Reverse();
171+
172+
public List<LogEventPropertyValue>? Complete()
173+
{
174+
var scopeItems = _scopeItems;
175+
_scopeItems = null;
176+
return scopeItems;
177+
}
173178
}
174179
}

0 commit comments

Comments
 (0)