I use serilog in my projects with the static logger approach - it's nice and easy to be able to call Log.X on my class libraries rather than injecting a logger class everywhere.
However when it comes to unit/integration testing, if a test has failed it would be hugely beneficial to see the error logs from the class libraries (moreso for integration tests).
Because I am not injecting an ILogger into my classes (due to use of static logger), I can't create a mock test logger that writes output to the test logs.
Has anyone managed to output messages to XUnit using the Serilog global (static) logger?
The Serilog.Sinks.XUnit nuget package makes it easy to accomplish this. Reference the nuget in your project. Then you can use the static logger in the test:
using Serilog;
using Xunit;
using Xunit.Abstractions;
namespace XunitToSerilog
{
public class SampleTest
{
public SampleTest(ITestOutputHelper output)
{
Log.Logger = new LoggerConfiguration()
// add the xunit test output sink to the serilog logger
// https://github.com/trbenning/serilog-sinks-xunit#serilog-sinks-xunit
.WriteTo.TestOutput(output)
.CreateLogger();
}
[Fact]
public void Test1()
{
Log.Information("goes to test output");
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With