XUnitLoggerProvider.cs 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. using Microsoft.Extensions.Logging;
  2. using Xunit.Abstractions;
  3. namespace Tests;
  4. public sealed class XUnitLoggerProvider : ILoggerProvider
  5. {
  6. private readonly ITestOutputHelper _output;
  7. public XUnitLoggerProvider(ITestOutputHelper output)
  8. {
  9. _output = output;
  10. }
  11. public ILogger CreateLogger(string categoryName)
  12. => new XUnitLogger(_output, categoryName);
  13. public void Dispose() { }
  14. private sealed class XUnitLogger : ILogger
  15. {
  16. private readonly ITestOutputHelper _output;
  17. private readonly string _category;
  18. public XUnitLogger(ITestOutputHelper output, string category)
  19. {
  20. _output = output;
  21. _category = category;
  22. }
  23. public IDisposable BeginScope<TState>(TState state) => null!;
  24. public bool IsEnabled(LogLevel logLevel) => true;
  25. public void Log<TState>(LogLevel logLevel, EventId eventId,
  26. TState state, Exception? exception, Func<TState, Exception?, string> formatter)
  27. {
  28. _output.WriteLine($"[{logLevel}] {_category}: {formatter(state, exception)}");
  29. }
  30. }
  31. }