Lesson 43 of 93 · 6 min read · Updated
Testing ILogger in .NET: Verify Log Level, EventId and Structured Properties
On this page
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
- .NET 11 SDK
- xUnit 2.9.3
- Moq 4.21.0
- FluentAssertions 7.2.2
- Microsoft.Extensions.TimeProvider.Testing 11.0.0
Microsoft.Extensions.Loggingabstractions (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
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
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
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
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
- Treat log level,
EventIdand structured properties as the log contract; the formatted sentence is not. - A recording
ILogger<T>turns each call into aLogEntrywith a property dictionary and gives readable tests. - Moq can verify
ILogger.Log<TState>withIt.IsAnyType, but the expression is hard to read and tends to check the text. - Verify both directions: the warning appears when it should, and no entry appears on the happy path.
- If a raw Moq logger expression repeats in your codebase, replace it with a recording logger or a helper.