XUnitLoggerProvider.cs 1.1 KB

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