Created
September 12, 2015 13:41
-
-
Save JakeGinnivan/520fd17d33297167843d to your computer and use it in GitHub Desktop.
XUnit to LibLog Bridge
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Simple bridge to allow capturing of LibLog log messages in xUnit 2.0 tests | |
// Usage: | |
private readonly ITestOutputHelper _outputHelper; | |
public Example(ITestOutputHelper outputHelper) { _outputHelper = outputHelper; } | |
[Test] | |
public void Test() | |
{ | |
using (LogHelper.Capture(_outputHelper, LogProvider.SetCurrentLogProvider)) | |
{ | |
// Call library code, log messages will be captured | |
} | |
} | |
public static class LogHelper | |
{ | |
private static readonly XUnitProvider Provider; | |
static LogHelper() | |
{ | |
Provider = new XUnitProvider(); | |
} | |
public static IDisposable Capture(ITestOutputHelper outputHelper, Action<ILogProvider> setProvider) | |
{ | |
// TODO Only do this once | |
setProvider(Provider); | |
CallContext.SetData("CurrentOutputHelper", outputHelper); | |
return new DelegateDisposable(() => | |
{ | |
CallContext.SetData("CurrentOutputHelper", null); | |
}); | |
} | |
class DelegateDisposable : IDisposable | |
{ | |
private readonly Action _action; | |
public DelegateDisposable(Action action) | |
{ | |
_action = action; | |
} | |
public void Dispose() | |
{ | |
_action(); | |
} | |
} | |
} | |
public class XUnitProvider : ILogProvider | |
{ | |
public Logger GetLogger(string name) | |
{ | |
return XUnitLogger; | |
} | |
private bool XUnitLogger(LogLevel logLevel, [CanBeNull] Func<string> messageFunc, [CanBeNull] Exception exception, params object[] formatParameters) | |
{ | |
if (messageFunc == null) return true; | |
var currentHelper = (ITestOutputHelper)CallContext.GetData("CurrentOutputHelper"); | |
if (currentHelper == null) | |
return false; | |
currentHelper.WriteLine("[{0}] {1}", logLevel, messageFunc()); | |
if (exception != null) | |
currentHelper.WriteLine("Exception:{0}{1}", Environment.NewLine, exception.ToString()); | |
return true; | |
} | |
public IDisposable OpenNestedContext(string message) | |
{ | |
throw new NotImplementedException(); | |
} | |
public IDisposable OpenMappedContext(string key, string value) | |
{ | |
throw new NotImplementedException(); | |
} | |
} |
For the above to work on netcoreapp2.0
or later, need a CallContext
shim from http://www.cazzulino.com/callcontext-netstandard-netcore.html
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
haha just googled for this :)