Skip to content

Instantly share code, notes, and snippets.

@djeikyb
Created April 14, 2021 21:23
Show Gist options
  • Save djeikyb/37f1e93590011b925be9cf7718ae0c83 to your computer and use it in GitHub Desktop.
Save djeikyb/37f1e93590011b925be9cf7718ae0c83 to your computer and use it in GitHub Desktop.
the simplest possible bridge between xunit and microsoft's ilogger
using System;
using Microsoft.Extensions.Logging;
using Xunit.Abstractions;
public class XunitLogger<T> : ILogger<T>
{
private readonly ITestOutputHelper _outputHelper;
public XunitLogger(ITestOutputHelper outputHelper)
{
_outputHelper = outputHelper;
}
public IDisposable BeginScope<TState>(TState state) => throw new NotImplementedException();
public bool IsEnabled(LogLevel logLevel) => true;
public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception exception,
Func<TState, Exception, string> formatter) =>
_outputHelper.WriteLine($"[{logLevel}] {formatter.Invoke(state, exception)}");
}
@djeikyb
Copy link
Author

djeikyb commented Apr 14, 2021

How to use in a test:

using Microsoft.Extensions.Logging;
using Xunit;
using Xunit.Abstractions;

public class Example
{
    private readonly ITestOutputHelper _testOutputHelper;

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

    [Fact]
    public void SomeTest()
    {
        var logger = new XunitLogger<Example>(_testOutputHelper);
        logger.LogError("some log message");
    }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment