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

Correct the order of property additions from external scopes #269

Merged
merged 1 commit into from
Mar 13, 2025
Merged
Show file tree
Hide file tree
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 @@ -102,9 +102,12 @@ public void Enrich(LogEvent logEvent, ILogEventPropertyFactory propertyFactory)
}
}

scopeItems?.Reverse();

_externalScopeProvider?.ForEachScope((state, accumulatingLogEvent) =>
{
SerilogLoggerScope.EnrichWithStateAndCreateScopeItem(accumulatingLogEvent, propertyFactory, state, out var scopeItem);
SerilogLoggerScope.EnrichWithStateAndCreateScopeItem(
accumulatingLogEvent, propertyFactory, state, update: true, out var scopeItem);

if (scopeItem != null)
{
Expand All @@ -115,7 +118,6 @@ public void Enrich(LogEvent logEvent, ILogEventPropertyFactory propertyFactory)

if (scopeItems != null)
{
scopeItems.Reverse();
logEvent.AddPropertyIfAbsent(new LogEventProperty(ScopePropertyName, new SequenceValue(scopeItems)));
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -47,9 +47,9 @@ public void Dispose()
}
}

public void EnrichAndCreateScopeItem(LogEvent logEvent, ILogEventPropertyFactory propertyFactory, out LogEventPropertyValue? scopeItem) => EnrichWithStateAndCreateScopeItem(logEvent, propertyFactory, _state, out scopeItem);
public void EnrichAndCreateScopeItem(LogEvent logEvent, ILogEventPropertyFactory propertyFactory, out LogEventPropertyValue? scopeItem) => EnrichWithStateAndCreateScopeItem(logEvent, propertyFactory, _state, update: false, out scopeItem);

public static void EnrichWithStateAndCreateScopeItem(LogEvent logEvent, ILogEventPropertyFactory propertyFactory, object? state, out LogEventPropertyValue? scopeItem)
public static void EnrichWithStateAndCreateScopeItem(LogEvent logEvent, ILogEventPropertyFactory propertyFactory, object? state, bool update, out LogEventPropertyValue? scopeItem)
{
if (state == null)
{
Expand All @@ -63,8 +63,8 @@ public static void EnrichWithStateAndCreateScopeItem(LogEvent logEvent, ILogEven
// Separate handling of this case eliminates boxing of Dictionary<TKey, TValue>.Enumerator.
scopeItem = null;
foreach (var stateProperty in dictionary)
{
AddProperty(logEvent, propertyFactory, stateProperty.Key, stateProperty.Value);
{
AddProperty(logEvent, propertyFactory, stateProperty.Key, stateProperty.Value, update);
}
}
else if (state is IEnumerable<KeyValuePair<string, object>> stateProperties)
Expand All @@ -79,21 +79,21 @@ public static void EnrichWithStateAndCreateScopeItem(LogEvent logEvent, ILogEven
}
else
{
AddProperty(logEvent, propertyFactory, stateProperty.Key, stateProperty.Value);
AddProperty(logEvent, propertyFactory, stateProperty.Key, stateProperty.Value, update);
}
}
}
#if FEATURE_ITUPLE
else if (state is System.Runtime.CompilerServices.ITuple tuple && tuple.Length == 2 && tuple[0] is string s)
{
scopeItem = null; // Unless it's `FormattedLogValues`, these are treated as property bags rather than scope items.
AddProperty(logEvent, propertyFactory, s, tuple[1]);
AddProperty(logEvent, propertyFactory, s, tuple[1], update);
}
#else
else if (state is ValueTuple<string, object?> tuple)
{
scopeItem = null;
AddProperty(logEvent, propertyFactory, tuple.Item1, tuple.Item2);
AddProperty(logEvent, propertyFactory, tuple.Item1, tuple.Item2, update);
}
#endif
else
Expand All @@ -102,22 +102,29 @@ public static void EnrichWithStateAndCreateScopeItem(LogEvent logEvent, ILogEven
}
}

static void AddProperty(LogEvent logEvent, ILogEventPropertyFactory propertyFactory, string key, object? value)
static void AddProperty(LogEvent logEvent, ILogEventPropertyFactory propertyFactory, string key, object? value, bool update)
{
var destructureObject = false;
var destructureObjects = false;

if (key.StartsWith('@'))
{
key = SerilogLogger.GetKeyWithoutFirstSymbol(SerilogLogger.DestructureDictionary, key);
destructureObject = true;
destructureObjects = true;
}
else if (key.StartsWith('$'))
{
key = SerilogLogger.GetKeyWithoutFirstSymbol(SerilogLogger.StringifyDictionary, key);
value = value?.ToString();
}

var property = propertyFactory.CreateProperty(key, value, destructureObject);
logEvent.AddPropertyIfAbsent(property);
var property = propertyFactory.CreateProperty(key, value, destructureObjects);
if (update)
{
logEvent.AddOrUpdateProperty(property);
}
else
{
logEvent.AddPropertyIfAbsent(property);
}
}
}
47 changes: 43 additions & 4 deletions test/Serilog.Extensions.Logging.Tests/SerilogLoggerTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,14 @@

using System.Collections;
using System.Diagnostics;
using Microsoft.Extensions.DependencyInjection;
using Serilog.Events;
using Microsoft.Extensions.Logging;
using Serilog.Debugging;
using Serilog.Extensions.Logging.Tests.Support;
using Xunit;
using Serilog.Core;
// ReSharper disable AccessToDisposedClosure

namespace Serilog.Extensions.Logging.Tests;

Expand All @@ -17,9 +19,9 @@ public class SerilogLoggerTest
const string Name = "test";
const string TestMessage = "This is a test";

static Tuple<SerilogLogger, SerilogSink> SetUp(LogLevel logLevel, IExternalScopeProvider? externalScopeProvider = null)
static Tuple<SerilogLogger, CollectingSink> SetUp(LogLevel logLevel, IExternalScopeProvider? externalScopeProvider = null)
{
var sink = new SerilogSink();
var sink = new CollectingSink();

var serilogLogger = new LoggerConfiguration()
.WriteTo.Sink(sink)
Expand All @@ -34,7 +36,7 @@ static Tuple<SerilogLogger, SerilogSink> SetUp(LogLevel logLevel, IExternalScope
provider.SetScopeProvider(externalScopeProvider);
}

return new Tuple<SerilogLogger, SerilogSink>(logger, sink);
return new Tuple<SerilogLogger, CollectingSink>(logger, sink);
}

[Fact]
Expand Down Expand Up @@ -516,7 +518,7 @@ public void Dispose()
}
}
}

[Fact]
public void MismatchedMessageTemplateParameterCountIsHandled()
{
Expand Down Expand Up @@ -579,4 +581,41 @@ public void TraceAndSpanIdsAreCaptured()
Assert.Equal(Activity.Current.TraceId, evt.TraceId);
Assert.Equal(Activity.Current.SpanId, evt.SpanId);
}

[Fact]
public void LoggingScopeReplacesPropertyInNestedScope()
{
var sink = new CollectingSink();
using var logger = new LoggerConfiguration().WriteTo.Sink(sink).CreateLogger();

var services = new ServiceCollection();
services.AddLogging(l => l.AddSerilog(logger));

using var serviceProvider = services.BuildServiceProvider();
var msLogger = serviceProvider.GetRequiredService<ILogger<SerilogLoggerTest>>();

using (msLogger.BeginScope(new Dictionary<string, object> { { "EXECUTION_TAGS", "[TAG1]" } }))
{
msLogger.LogInformation("Message1");
using (msLogger.BeginScope(new Dictionary<string, object> { { "EXECUTION_TAGS", "[TAG2]" } }))
{
msLogger.LogInformation("Message2");
}
}

var logEvent = sink.Writes.FirstOrDefault(e => e.MessageTemplate.Text == "Message1");
Assert.NotNull(logEvent);
AssertHasScalarProperty(logEvent, "EXECUTION_TAGS", "[TAG1]");

logEvent = sink.Writes.FirstOrDefault(e => e.MessageTemplate.Text == "Message2");
Assert.NotNull(logEvent);
AssertHasScalarProperty(logEvent, "EXECUTION_TAGS", "[TAG2]");
}

static void AssertHasScalarProperty(LogEvent logEvent, string name, object? expectedValue)
{
Assert.True(logEvent.Properties.TryGetValue(name, out var result));
var scalar = Assert.IsType<ScalarValue>(result);
Assert.Equal(expectedValue, scalar.Value);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ public void AddSerilogMustRegisterAnILoggerProvider()
[Fact]
public void AddSerilogMustRegisterAnILoggerProviderThatForwardsLogsToStaticSerilogLogger()
{
var sink = new SerilogSink();
var sink = new CollectingSink();
Log.Logger = new LoggerConfiguration()
.WriteTo.Sink(sink)
.CreateLogger();
Expand All @@ -39,7 +39,7 @@ public void AddSerilogMustRegisterAnILoggerProviderThatForwardsLogsToStaticSeril
[Fact]
public void AddSerilogMustRegisterAnILoggerProviderThatForwardsLogsToProvidedLogger()
{
var sink = new SerilogSink();
var sink = new CollectingSink();
var serilogLogger = new LoggerConfiguration()
.WriteTo.Sink(sink)
.CreateLogger();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@

namespace Serilog.Extensions.Logging.Tests.Support;

public class SerilogSink : ILogEventSink
public class CollectingSink : ILogEventSink
{
public List<LogEvent> Writes { get; set; } = new();

Expand Down