Testing your Logs in .NET Core
Why should you even care about your logs?
A while back I posted a video about the use of OTEL inside the testing process.
While I'd avoid writing tests for the traces, there might be cases where you need to test your logs.
A simple example is: an alert that you generate based on a specific log message.
In such cases you'd generally have a test that ensures the consistency of the said message.
Because changes to the message might/will break your alerting.
Let's take a look at a simple example of how you can test the logs your system generates.
Getting started:
I'm going to use the app I've been building so far during the testing newsletter chain, which you can find here on substack.
The card game API is using Serilog library for logging, it comes with the concept of Sinks which we are going to leverage.
If you have never used Serilog in the past here are a couple of tutorials I put together:
TLDR: We will set-up an in-memory tests sink for Serilog to push the logs into, which we will query afterwards in the Assert part of the tests.
To do that we will have to install the following NuGet packages:
Serilog.Sinks.InMemory (the sink itself)
Serilog.Sinks.InMemory.Assertions (a fluent assertion extension for ease of use)
From here on out it's a bit tricky. The sink from the library is AsyncLocal which results in a few surprises when using with the WebApplicationFactory.
— You can read more here and here.
That said the fix itself is easy, we will need to create a wrapper around the sink. It will look like this:
Once we have the wrapper we should reconfigure Serilog inside the WebApplicationFactory to use this sink.
PS: if you want you can add loggingBuilder.ClearProviders(); between line 14/15 if you want to leave only the in-memory sink.
Now we will need a way to retrieve the said sink, which can be done relatively easy using the WaF:
In our tests inside the constructor you can set up a easy way to access the sink:
Finally here is what a test that aims to verify for a specific log message would look like:
Sum up and Next steps
Testing your logs is a practice that has it’s place and is relatively easy to set up given the right tools.
If you liked this kind of content/tutorial I will be really grateful if you cloud share it among your colleagues and friends in order to grow the newsletter further.
Heads up:
I release an entire course around the topic of building a Modular Monolith system that you can find clicking here : Microservices Ready Architecture
Become a Patreon and get access to the source code presented in the newsletters and YouTube channel.
And with that cya next time :-)