Skip to content

Instantly share code, notes, and snippets.

@djeikyb
Last active October 20, 2021 22:10
Show Gist options
  • Save djeikyb/cf8f81e6917335b346534f5f072a1242 to your computer and use it in GitHub Desktop.
Save djeikyb/cf8f81e6917335b346534f5f072a1242 to your computer and use it in GitHub Desktop.
A barely functional logger to standard out for xunit
using System;
using Microsoft.Extensions.Logging;
using Xunit.Abstractions;
namespace Example
{
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.ToString()[..3]}] {formatter.Invoke(state, exception)}\n\n{exception}");
}
}
@djeikyb
Copy link
Author

djeikyb commented Oct 20, 2021

A similar hack around xunit's determined hostility:

using System.IO;
using System.Text;
using Xunit.Abstractions;

namespace Example
{
    public class XunitTextWriter : TextWriter
    {
        private readonly ITestOutputHelper _output;
        public XunitTextWriter(ITestOutputHelper output) => _output = output;
        public override Encoding Encoding { get; } = Encoding.UTF8;
        public override void WriteLine(string value) => _output.WriteLine(value);
    }
}

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