Skip to content

Commit

Permalink
feat: Add ToString override to CorrelatedLogScope (#110)
Browse files Browse the repository at this point in the history
* Add ToStirng override to CorrelatedLogScope

Output to the default Console logger uses `ToString` on scope items.

* test: add coverage and simplify with concatenation

---------

Co-authored-by: skwasjer <[email protected]>
  • Loading branch information
e-salmon and skwasjer authored Sep 8, 2024
1 parent 9e5c991 commit b979581
Show file tree
Hide file tree
Showing 2 changed files with 73 additions and 0 deletions.
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)));
}
}

0 comments on commit b979581

Please sign in to comment.