Skip to content
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 @@ -396,14 +396,26 @@ private static bool CustomFormatter<TState>(TState state, Exception exception, o
return false;

#if NET8_0_OR_GREATER
var stateKeys = (state as IEnumerable<KeyValuePair<string, object>>)?
.ToDictionary(i => i.Key, i => PowertoolsLoggerHelpers.ObjectToDictionary(i.Value));
var stateKeys = new Dictionary<string, object>();
if (state is IEnumerable<KeyValuePair<string, object>> keyValuePairs)
{
foreach (var kvp in keyValuePairs)
{
stateKeys[kvp.Key] = PowertoolsLoggerHelpers.ObjectToDictionary(kvp.Value);
}
}
#else
var stateKeys = (state as IEnumerable<KeyValuePair<string, object>>)?
.ToDictionary(i => i.Key, i => i.Value);
var stateKeys = new Dictionary<string, object>();
if (state is IEnumerable<KeyValuePair<string, object>> keyValuePairs)
{
foreach (var kvp in keyValuePairs)
{
stateKeys[kvp.Key] = kvp.Value;
}
}
#endif

if (stateKeys is null || stateKeys.Count != 2)
if (stateKeys.Count != 2)
return false;

if (!stateKeys.TryGetValue(_originalformat, out var originalFormat))
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1750,6 +1750,48 @@ public void Log_Cold_Start(bool willLog, string awsInitType)
// Assert
Assert.Contains($"\"coldStart\":{willLog.ToString().ToLower()}", outPut);
}

[Fact]
public void Log_WhenDuplicateKeysInState_LastValueWins()
{
// Arrange
var loggerName = Guid.NewGuid().ToString();
var service = Guid.NewGuid().ToString();
var logLevel = LogLevel.Information;

var configurations = Substitute.For<IPowertoolsConfigurations>();
configurations.Service.Returns(service);
configurations.LogLevel.Returns(logLevel.ToString());
configurations.LoggerOutputCase.Returns(LoggerOutputCase.PascalCase.ToString());

var systemWrapper = Substitute.For<IConsoleWrapper>();

var loggerConfiguration = new PowertoolsLoggerConfiguration
{
Service = service,
MinimumLogLevel = logLevel,
LoggerOutputCase = LoggerOutputCase.PascalCase,
LogOutput = systemWrapper
};

var provider = new PowertoolsLoggerProvider(loggerConfiguration, configurations);
var logger = provider.CreateLogger(loggerName);

// Create state with duplicate keys (simulating duplicate HTTP headers)
var stateWithDuplicates = new List<KeyValuePair<string, object>>
{
new("Content-Type", "application/json"),
new("Content-Type", "application/x-www-form-urlencoded"), // This should win
new("Accept", "text/html"),
new("Accept", "*/*") // This should win
};

// Act - This should not throw an exception
logger.Log(logLevel, new EventId(), stateWithDuplicates, null, (state, ex) => "Test message");

// Assert
systemWrapper.Received(1).WriteLine(Arg.Any<string>());
}

public void Dispose()
{
Expand Down
Loading