Skip to content

Instantly share code, notes, and snippets.

@JakeGinnivan
Last active June 20, 2016 16:31
Show Gist options
  • Save JakeGinnivan/8fd55a3482b499334d5c4c7e9590d61c to your computer and use it in GitHub Desktop.
Save JakeGinnivan/8fd55a3482b499334d5c4c7e9590d61c to your computer and use it in GitHub Desktop.
Helpers for xunit 2 to enable logging through Serilogs static Log type
public class LoggingTestBase : IDisposable
{
readonly IDisposable _logger;
static LoggingTestBase()
{
var loggerConfiguration = new LoggerConfiguration();
Log.Logger = loggerConfiguration
.WriteTo.Sink(new SerilogTestSink())
.Enrich.FromLogContext()
.CreateLogger();
}
protected LoggingTestBase(ITestOutputHelper outputHelper)
{
_logger = LogHelper.Capture(outputHelper);
}
public virtual void Dispose()
{
_logger.Dispose();
}
}
public static class LogHelper
{
static readonly ConcurrentDictionary<Guid, ITestOutputHelper> LoggerLookup = new ConcurrentDictionary<Guid, ITestOutputHelper>();
public static void Log(string log)
{
var currentCorrelationId = (Guid?)CallContext.LogicalGetData("TestCorrelationId");
if (currentCorrelationId == null)
return;
LoggerLookup[currentCorrelationId.Value].WriteLine(log);
}
static void AddOutputHelper(Guid correlationId, ITestOutputHelper outputHelper)
{
if (outputHelper == null)
throw new ArgumentNullException(nameof(outputHelper));
LoggerLookup.TryAdd(correlationId, outputHelper);
}
static void RemoveOutputHelper(Guid correlationId)
{
ITestOutputHelper removedHelper;
LoggerLookup.TryRemove(correlationId, out removedHelper);
}
public static IDisposable Capture(ITestOutputHelper outputHelper)
{
if (outputHelper == null)
throw new ArgumentNullException(nameof(outputHelper));
var correlationId = Guid.NewGuid();
AddOutputHelper(correlationId, outputHelper);
CallContext.LogicalSetData("TestCorrelationId", correlationId);
return new DelegateDisposable(() =>
{
RemoveOutputHelper(correlationId);
CallContext.LogicalSetData("TestCorrelationId", null);
});
}
class DelegateDisposable : IDisposable
{
private readonly Action _action;
public DelegateDisposable(Action action)
{
_action = action;
}
public void Dispose()
{
_action();
}
}
}
public class SerilogTestSink : ILogEventSink
{
public void Emit(LogEvent logEvent)
{
LogHelper.Log(logEvent.RenderMessage());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment