How to write logs from ILogger to xUnit.net ITestOutputHelper

 
 
  • Gérald Barré

When a test fails, it's important to understand what happened. All information could be useful. If you are using ILogger in your application, you can use the logs to understand what happened. However, the logs are not displayed in the output of xUnit. You can change this behavior by using a custom ILoggerProvider implementation that writes the logs to ITestOutputHelper. I've already written about this subject a few years ago, but I've decided to create a NuGet package to ease the use.

You can use the following NuGet package to get the XUnitLoggerProvider:

Shell
dotnet add package Meziantou.Extensions.Logging.Xunit
C#
public class UnitTest1
{
    private readonly ITestOutputHelper _testOutputHelper;

    public UnitTest1(ITestOutputHelper testOutputHelper)
    {
        _testOutputHelper = testOutputHelper;
    }

    [Fact]
    public async Task Test1()
    {
        using var factory = new WebApplicationFactory<Program>()
            .WithWebHostBuilder(builder =>
            {
                builder.ConfigureLogging(builder =>
                {
                    // You can override the logging configuration if needed
                    //builder.SetMinimumLevel(LogLevel.Trace);
                    //builder.AddFilter(_ => true);

                    // Register the xUnit logger provider
                    builder.Services.AddSingleton<ILoggerProvider>(new XUnitLoggerProvider(_testOutputHelper, appendScope: false));
                });
            });

        // Call the method to test
        using var client = factory.CreateClient();
        var str = await client.GetStringAsync("/user/me");

        // Make sure the test fails, so the logs are displayed
        Assert.Fail("");
    }
}

You can now view the logs of the application in the test explorer:

The output is also available when using dotnet test, and so when running on the CI:

Last but not least, the logs are also available in the trx ou junit files. So, you can get a good experience in Visual Studio, in the CLI, and when using your favorite CI tool.

Do you have a question or a suggestion about this post? Contact me!

Follow me:
Enjoy this blog?Buy Me A Coffee💖 Sponsor on GitHub