Wednesday, June 24, 2015

Capture xUnit Test Output with NLog and Common Logging

I recently blogged about How To Capture Test Output in xUnit 2.0. This is great, but how can we pass the ITestOutputHelper into our code to capture log output?

You could just wrap the xUnit helper in an ILog or ILogger, but we can also take it a step further and get all of the NLog features too! By creating an NLog target that wraps the ITestOutputHelper we can enable ourselves to use multiple targets, layouts, variables, verbosity levels, and more.

Sample Unit Test

public class NLogTests : IDisposable
    private readonly ILogger _logger;
    public NLogTests(ITestOutputHelper outputHelper)
        _logger = outputHelper.GetNLogLogger();
    public void Dispose()
    public void Hello()
        _logger.Trace("World Trace");
        _logger.Debug("World Debug");
        _logger.Warn("World Warn");
        _logger.Error("World Error");

Sample App.config

<nlog xmlns="" 
    <add assembly="xunit.NLog" />
  <targets async="false">
    <target xsi:type="TestOutput"
      name="Test" />
    <logger name="*" minlevel="Debug" writeTo="Test" />


1 comment:

  1. _logger = outputHelper.GetNLogLogger(); -- at this line in my code I am getting an exception of an instance not set to an object....having a little trouble understanding why


Real Time Web Analytics