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

feat: Add ToString override to CorrelatedLogScope #110

Merged
merged 2 commits into from
Sep 8, 2024
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
9 changes: 9 additions & 0 deletions src/Correlate.Core/Extensions/LoggerExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -49,5 +49,14 @@ public KeyValuePair<string, object> this[int index]
throw new ArgumentOutOfRangeException(nameof(index));
}
}

/// <summary>
/// Returns a representation of the scope items as a list of comma-separated items,
/// matching the default representation provided by the standard Console logger.
/// </summary>
public override string ToString()
{
return _scopeKey + ':' + _correlationId;
}
}
}
64 changes: 64 additions & 0 deletions test/Correlate.Core.Tests/Extensions/LoggerExtensionsTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
using Microsoft.Extensions.Logging;

namespace Correlate.Extensions;

public sealed class LoggerExtensionsTests
{
private readonly ILogger _logger;

public LoggerExtensionsTests()
{
_logger = Substitute.For<ILogger>();
}

[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<string, object>(scopeKey, correlationId);

Func<IReadOnlyList<KeyValuePair<string, object>>, bool> assertScope = kvps =>
{
kvps.Should()
.ContainSingle()
.Which.Should()
.Be(expectedKvp);
return true;
};

// Act
_logger.BeginCorrelatedScope(scopeKey, correlationId);

// Assert
_logger.Received(1).BeginScope(Arg.Is<IReadOnlyList<KeyValuePair<string, object>>>(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<object, bool> assertScope = formattable =>
{
formattable.ToString().Should().Be(expectedStr);
return true;
};

// Act
_logger.BeginCorrelatedScope(scopeKey, correlationId);

// Assert
_logger.Received(1).BeginScope(Arg.Is<object>(e => assertScope(e)));
}
}
Loading