Minimalist Microsoft Extensions Logging Provider
- .NET Standard 2.0 library
- compatible with xUnit, NUnit, MSTest and other test frameworks
- customizable formatting
- supports scopes
- supports Microsoft.Extensions.DependencyInjection
- dependencies: Microsoft.Extensions.Logging
PM> Install-Package MXLogger
using Microsoft.Extensions.Logging;
using Xunit;
namespace Xunit.Abstractions;
// This class may be used as the base class for test classes.
public abstract class XunitTestBase
{
private readonly ITestOutputHelper Output;
protected readonly ILoggerFactory LogFactory;
protected readonly ILogger Logger;
protected void Write(string format, params object[] args) =>
Output.WriteLine(string.Format(format, args) + Environment.NewLine);
protected XunitTestBase(ITestOutputHelper output, LogLevel logLevel = LogLevel.Debug, string name = "Test")
{
Output = output;
LogFactory = LoggerFactory.Create(builder => builder
.AddMXLogger(output.WriteLine)
.SetMinimumLevel(logLevel));
Logger = LogFactory.CreateLogger(name);
}
}
using Microsoft.Extensions.Logging;
using Xunit;
using Xunit.Abstractions;
namespace YourNamespace;
public class SimpleExample : XunitTestBase
{
public SimpleExample(ITestOutputHelper output) : base(output) { }
[Fact]
public void Test()
{
Logger.LogInformation("message!");
Write("test!");
}
}
output:
Info: Test
message!
test!
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.DependencyInjection;
using Xunit;
using Xunit.Abstractions;
public class MyComponent
{
private readonly ILogger Logger;
public MyComponent(ILogger<MyComponent> logger)
{
Logger = logger;
}
public void Run()
{
Logger.LogCritical("Message");
...
}
}
public class DependencyInjectionTest
{
private readonly MyComponent MyComponent;
public DependencyInjectionTest(ITestOutputHelper output)
{
MyComponent = new ServiceCollection()
.AddTransient<MyComponent>()
.AddLogging(builder => builder
.AddMXLogger(output.WriteLine)
.SetMinimumLevel(LogLevel.Debug))
.BuildServiceProvider()
.GetRequiredService<MyComponent>();
}
[Fact]
public void Test()
{
MyComponent.Run();
...
}
}
output:
Crit: MyNamespace.MyComponent
Message