diff --git a/src/Correlate.Core/Extensions/LoggerExtensions.cs b/src/Correlate.Core/Extensions/LoggerExtensions.cs index 66e2443..df1fd90 100644 --- a/src/Correlate.Core/Extensions/LoggerExtensions.cs +++ b/src/Correlate.Core/Extensions/LoggerExtensions.cs @@ -49,5 +49,14 @@ public KeyValuePair this[int index] throw new ArgumentOutOfRangeException(nameof(index)); } } + + /// + /// Returns a representation of the scope items as a list of comma-separated items, + /// matching the default representation provided by the standard Console logger. + /// + public override string ToString() + { + return _scopeKey + ':' + _correlationId; + } } } diff --git a/test/Correlate.Core.Tests/Extensions/LoggerExtensionsTests.cs b/test/Correlate.Core.Tests/Extensions/LoggerExtensionsTests.cs new file mode 100644 index 0000000..488b888 --- /dev/null +++ b/test/Correlate.Core.Tests/Extensions/LoggerExtensionsTests.cs @@ -0,0 +1,64 @@ +using Microsoft.Extensions.Logging; + +namespace Correlate.Extensions; + +public sealed class LoggerExtensionsTests +{ + private readonly ILogger _logger; + + public LoggerExtensionsTests() + { + _logger = Substitute.For(); + } + + [Theory] + [InlineData(CorrelateConstants.CorrelationIdKey, "12345")] + [InlineData("CustomKey", "abcdef")] + public void When_beginning_scope_it_should_return_disposable_scope_implementing_kvp_list_containing_the_correlation_id + ( + string scopeKey, + string correlationId + ) + { + var expectedKvp = new KeyValuePair(scopeKey, correlationId); + + Func>, bool> assertScope = kvps => + { + kvps.Should() + .ContainSingle() + .Which.Should() + .Be(expectedKvp); + return true; + }; + + // Act + _logger.BeginCorrelatedScope(scopeKey, correlationId); + + // Assert + _logger.Received(1).BeginScope(Arg.Is>>(e => assertScope(e))); + } + + [Theory] + [InlineData(CorrelateConstants.CorrelationIdKey, "12345")] + [InlineData("CustomKey", "abcdef")] + public void When_formatting_scope_it_should_return_expected + ( + string scopeKey, + string correlationId + ) + { + string expectedStr = $"{scopeKey}:{correlationId}"; + + Func assertScope = formattable => + { + formattable.ToString().Should().Be(expectedStr); + return true; + }; + + // Act + _logger.BeginCorrelatedScope(scopeKey, correlationId); + + // Assert + _logger.Received(1).BeginScope(Arg.Is(e => assertScope(e))); + } +}