How to add debug logging to C# .NET Core unit tests?

Since you're using .NET Core, I'll assume you're also using XUnit.

XUnit uses a specific interface for logging to the console, ITestOutputHelper, which gets injected by XUnit itself in test fixture constructors.

There is a nuget package https://www.nuget.org/packages/Divergic.Logging.Xunit that can create an ILogger<T> wrapper around ITextOutputHelper to be able to pass them to systems that require the ILogger interface.

I don't use a dependency injection framework for my XUnit tests and I end up wiring them up myself with mock versions, so here's what I do.

public sealed class MyTestFixture
{
    private readonly ILogger<MyClass> _logger;

    public MyTestFixture(ITestOuputHelper helper)
    {
        _logger = helper.BuildLoggerFor<MyClass>();
    }

    [Fact]
    public void FooBar()
    {
        var myClass = new MyClass(_logger);
        myClass.WizzBang();
    }
}

Use the AddLogging(IServiceCollection, Action<ILoggingBuilder>) overload

var serviceProvider = new ServiceCollection()
    .AddLogging(builder => {
        builder.AddDebug();  //<--

        //...add other logging configuration as needed
    })
    .BuildServiceProvider();

//...

Which gives access to the builder via a configuration delegate


Following up on Matthews answer, per the xUnit docs here https://xunit.net/docs/capturing-output it is simple to add console logging to any unit test as per the example from their site:

using Xunit;
using Xunit.Abstractions;

public class MyTestClass
{
    private readonly ITestOutputHelper output;

    public MyTestClass(ITestOutputHelper output)
    {
        this.output = output;
    }

    [Fact]
    public void MyTest()
    {
        var temp = "my class!";
        output.WriteLine("This is output from {0}", temp);
    }
}