MES-ETL/MesETL.Test/XUnit/Logging/XUnitLogger.cs

39 lines
1.2 KiB
C#
Raw Normal View History

2024-12-10 14:03:09 +08:00
using Microsoft.Extensions.Logging;
using Xunit.Abstractions;
namespace TestProject1.XUnit.Logging;
/// <summary>
/// 适用于Xunit的日志记录器使用ITestOutputHelper输出
/// </summary>
public class XunitLogger : ILogger
{
private readonly ITestOutputHelper _testOutputHelper;
private readonly string _categoryName;
public XunitLogger(ITestOutputHelper testOutputHelper, string categoryName)
{
_testOutputHelper = testOutputHelper;
_categoryName = categoryName;
}
public IDisposable? BeginScope<TState>(TState state) where TState : notnull
=> NoopDisposable.Instance;
public bool IsEnabled(LogLevel logLevel)
=> true;
public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception? exception,
Func<TState, Exception?, string> formatter)
{
_testOutputHelper.WriteLine($"{_categoryName} [{eventId}] {formatter(state, exception)}");
if (exception != null)
_testOutputHelper.WriteLine(exception.ToString());
}
private class NoopDisposable : IDisposable
{
public static readonly NoopDisposable Instance = new();
public void Dispose() { }
}
}