Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Output logs to Xunit using Serilog Static Logger

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?

like image 810
aspirant_sensei Avatar asked Nov 18 '19 11:11

aspirant_sensei


1 Answers

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");
        }
    }
}
like image 58
rachri Avatar answered Oct 21 '22 10:10

rachri