An xUnit Microsoft.Extensions.Logging.ILoggerProvider that writes logs to the test output.
Its formatting and its configuration are based on the Microsoft.Extensions.Logging.Console.SimpleConsoleFormatter created from the ConsoleLoggerExtensions.AddSimpleConsole Method.
Install Devodo.Logging.Xunit as a NuGet package:
Install-Package Devodo.Logging.XunitOr via the .NET command line interface:
dotnet add package Devodo.Logging.XunitpublicclassBasicExampleTests(ITestOutputHelperoutputHelper){privatereadonlyILogger<BasicExampleTests>_logger=outputHelper.CreateLogger<BasicExampleTests>();[Fact]publicvoidTest(){_logger.LogInformation("This is a log message from the test.");}}Given a simple ASP.NET Minimal API as follows:
varapp=WebApplication.Create(args);app.MapGet("/echo/{message}",(stringmessage,ILogger<Program>logger)=>{logger.LogInformation("Handling echo request with input: {Message}",message);returnmessage;});app.Run();The application logs can be sent to xUnit test output as follows:
publicclassExampleTests{privatereadonlyITestOutputHelper_outputHelper;publicExampleTests(ITestOutputHelperoutputHelper){_outputHelper=outputHelper;}[Fact]publicasyncTaskGivenHttpClient_WhenGetRoot_ThenRespondsHello(){// ARRANGEvarhttpClient=newWebApplicationFactory<Program>().WithWebHostBuilder(builder =>{builder.ConfigureLogging(logging =>{// Add an xUnit logging provider that writes to the ITestOutputHelperlogging.AddXunit(_outputHelper);});}).CreateClient();// ACTvarresponse=awaithttpClient.GetAsync("/echo/hello xunit logging");// ASSERTAssert.Equal("hello xunit logging",awaitresponse.Content.ReadAsStringAsync());}}The output from the test above is:
info: Program[0]
Handling echo request with input: hello xunit logging
The following format options can be configured:
logging.AddXunit(_outputHelper, options =>{options.IncludeScopes=true;options.TimestampFormat="HH:mm:ss ";options.SingleLine=false;options.UseUtcTimestamp=true;});