Lesson 43 of 93 · 6 min read · Updated

Testing ILogger in .NET: Verify Log Level, EventId and Structured Properties

Logs are often part of a service's contract. Alerts, dashboards and support tools search for a specific event at a specific level. If a refactoring removes a warning, nobody notices until an incident. This lesson shows how to verify ILogger<T> calls in unit tests: first with a small recording logger, which is readable, then with a raw Moq expression, which works but is hard to read. It also explains what to assert on: level, event id and structured properties, not the formatted sentence.

Technical Requirements

  1. .NET 11 SDK
  2. xUnit 2.9.3
  3. Moq 4.21.0
  4. FluentAssertions 7.2.2
  5. Microsoft.Extensions.TimeProvider.Testing 11.0.0
  6. Microsoft.Extensions.Logging abstractions (part of the shared framework in .NET 11)

The Log Call Under Test

CheckoutService writes a warning when a coupon is unknown or expired. It uses a static EventId and a message template with a named placeholder.

M05.TestableDesign/CheckoutService.cs

/// <summary>Log event used when a coupon is not found or has expired.</summary>
public static readonly EventId CouponRejected = new(1001, nameof(CouponRejected));

// ...

if (coupon is null || !coupon.IsValidAt(now))
{
// Structured log: the contract is the event id and the properties,
// not the message text.
logger.LogWarning(
CouponRejected,
"Kupon reddedildi. Kod: {CouponCode}",
couponCode);
}

The template reads "Coupon rejected. Code: {CouponCode}". The logging infrastructure does not just build a string from it. It keeps {CouponCode} as a named property with the actual value. Log stores such as Seq, Elastic or Application Insights index that property, so an operator can search for every rejection of a specific code.

That gives three things worth testing: the level (Warning), the event id (1001), and the CouponCode property. The sentence itself is for humans and may change.

A Recording Logger

ILogger.Log<TState> is generic and takes a formatter delegate, which makes it awkward to mock. A small hand-written logger that records every entry is easier.

M05.TestableDesign.Tests/Doubles/RecordingLogger.cs

using Microsoft.Extensions.Logging;

namespace M05.TestableDesign.Tests.Doubles;

/// <summary>A single recorded log entry.</summary>
public sealed record LogEntry(LogLevel Level, EventId EventId, string Message, IReadOnlyDictionary<string, object?> State);

/// <summary>
/// ILogger.Log(...) has a generic and complex signature; verifying it with Moq
/// produces hard-to-read expressions. A small RECORDING logger does the same job
/// far more readably.
///
/// What should be verified?
/// LogLevel and EventId -> part of the contract (alerts/metrics rely on them)
/// Structured properties -> such as {CouponCode}
/// NOT the full formatted text -> the test breaks for nothing when the sentence changes
/// </summary>
public sealed class RecordingLogger<T> : ILogger<T>
{
private readonly List<LogEntry> _entries = [];

public IReadOnlyList<LogEntry> Entries => _entries;

public IDisposable BeginScope<TState>(TState state) where TState : notnull => NullScope.Instance;

public bool IsEnabled(LogLevel logLevel) => true;

public void Log<TState>(
LogLevel logLevel,
EventId eventId,
TState state,
Exception? exception,
Func<TState, Exception?, string> formatter)
{
// We turn the structured properties into a dictionary: this is the real contract.
var properties = state is IReadOnlyList<KeyValuePair<string, object?>> values
? values.ToDictionary(kv => kv.Key, kv => kv.Value)
: [];

_entries.Add(new LogEntry(logLevel, eventId, formatter(state, exception), properties));
}

private sealed class NullScope : IDisposable
{
public static readonly NullScope Instance = new();
public void Dispose() { }
}
}

The key line is the cast to IReadOnlyList<KeyValuePair<string, object?>>. The state object that LogWarning creates implements that interface, and its entries are the named placeholders plus an {OriginalFormat} entry with the template. Turning them into a dictionary gives the test direct access to CouponCode.

IsEnabled returns true so that no call is filtered out. BeginScope returns a no-op disposable because these tests do not use scopes.

The Readable Test

M05.TestableDesign.Tests/LoggerVerificationTests.cs

[Fact]
public async Task PayAsync_WithUnknownCoupon_LogsWarningWithStructuredCouponCode()
{
// Arrange
var logger = new RecordingLogger<CheckoutService>();
var coupons = new Mock<ICouponRepository>();
coupons
.Setup(x => x.FindAsync(It.IsAny<string>(), It.IsAny<CancellationToken>()))
.ReturnsAsync((Coupon?)null);

var sut = new CheckoutService(
ApprovingGateway().Object, coupons.Object, new FakeTimeProvider(Now), logger);

// Act
await sut.PayAsync(Money.Try(100m), "GECERSIZ");

// Assert - LEVEL, EVENT ID and STRUCTURED PROPERTY.
var entry = logger.Entries.Should().ContainSingle().Subject;
entry.Level.Should().Be(LogLevel.Warning);
entry.EventId.Should().Be(CheckoutService.CouponRejected);
entry.State["CouponCode"].Should().Be("GECERSIZ");

// We do not verify the whole formatted sentence - so the test does not break when the text changes.
}

ApprovingGateway() is a small helper in the same class that returns a gateway mock approving every authorization. (Coupon?)null tells Moq which overload of ReturnsAsync to use; without the cast the call is ambiguous.

ContainSingle().Subject asserts that exactly one entry was written and gives you that entry. Each of the next three lines maps to one part of the contract. The coupon code "GECERSIZ" means "invalid".

A second test checks the opposite case: with a valid coupon, logger.Entries.Should().BeEmpty(). A warning that fires on every successful checkout is also a bug, because it floods the log and hides real problems.

The Same Check with Moq

You can verify the same call on a Mock<ILogger<CheckoutService>>. It works, but look at the expression.

M05.TestableDesign.Tests/LoggerVerificationTests.cs

[Fact]
public async Task PayAsync_WithUnknownCoupon_CanAlsoBeVerifiedWithMoq()
{
// The Moq version of the same check. It WORKS but is hard to read;
// ILogger.Log is generic, so it needs workarounds like It.IsAnyType.
// If this expression repeats in your team, write an extension method or a recording logger.
var logger = new Mock<ILogger<CheckoutService>>();
var coupons = new Mock<ICouponRepository>();
coupons
.Setup(x => x.FindAsync(It.IsAny<string>(), It.IsAny<CancellationToken>()))
.ReturnsAsync((Coupon?)null);

var sut = new CheckoutService(
ApprovingGateway().Object, coupons.Object, new FakeTimeProvider(Now), logger.Object);

await sut.PayAsync(Money.Try(100m), "GECERSIZ");

logger.Verify(
x => x.Log(
LogLevel.Warning,
CheckoutService.CouponRejected,
It.Is<It.IsAnyType>((state, _) => state != null && state.ToString()!.Contains("GECERSIZ")),
It.IsAny<Exception?>(),
It.IsAny<Func<It.IsAnyType, Exception?, string>>()),
Times.Once);
}

LogWarning is an extension method, and Moq cannot intercept extension methods. So the test must verify the underlying Log<TState> method. Because TState is an internal type, the expression uses It.IsAnyType as a placeholder and a predicate on its ToString(). That predicate checks the formatted text, which is exactly what we wanted to avoid.

If you prefer not to maintain your own recording logger, Microsoft ships one: FakeLogger<T> in the Microsoft.Extensions.Diagnostics.Testing package records entries with their level, event id and structured state in the same way. The recording logger here is about forty lines, so writing it yourself is also a reasonable choice, and it shows exactly what the test depends on.

Pitfall: Asserting on the Sentence

Asserting entry.Message.Should().Be("Kupon reddedildi. Kod: GECERSIZ") looks precise, but it breaks when someone fixes a typo or translates the message. Nothing a user or an operator depends on has changed. Assert on level, event id and properties; leave the wording free.

Summary

  1. Treat log level, EventId and structured properties as the log contract; the formatted sentence is not.
  2. A recording ILogger<T> turns each call into a LogEntry with a property dictionary and gives readable tests.
  3. Moq can verify ILogger.Log<TState> with It.IsAnyType, but the expression is hard to read and tends to check the text.
  4. Verify both directions: the warning appears when it should, and no entry appears on the happy path.
  5. If a raw Moq logger expression repeats in your codebase, replace it with a recording logger or a helper.