9

I'm trying to add some simple console logging to my unit tests in ASP.NET Core 2.2 and am having trouble since the logging configuration changed.

I currently have this code, which creates a logger for my class, "DataTests":

// Create logger for our unit tests
var serviceProvider = new ServiceCollection()
    .AddLogging()
    .BuildServiceProvider();

var factory = serviceProvider.GetService<ILoggerFactory>();

var logger = factory.CreateLogger<DataTests>();

But it doesn't log to the debug window, and I can't configure it. I would like to do something like

factory.AddDebug();

But that extension is now obsolete and no longer available. It is replaced by an extension on ILoggingBuilder instead of ILoggerFactory. This is how it's used in file program.cs:

public static void Main(string[] args)
{
    var webHost = new WebHostBuilder()
        .UseKestrel()
        .UseContentRoot(Directory.GetCurrentDirectory())
        .ConfigureAppConfiguration((hostingContext, config) =>
        {
            var env = hostingContext.HostingEnvironment;
            config.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
                  .AddJsonFile($"appsettings.{env.EnvironmentName}.json",
                      optional: true, reloadOnChange: true);
            config.AddEnvironmentVariables();
        })
        .ConfigureLogging((hostingContext, logging) =>
        {
            // Requires `using Microsoft.Extensions.Logging;`
            logging.AddConfiguration(hostingContext.Configuration.GetSection("Logging"));
            logging.AddConsole();
            logging.AddDebug();
            logging.AddEventSourceLogger();
        })
        .UseStartup<Startup>()
        .Build();

    webHost.Run();
}

My problem is I don't know how to get the ILoggingBuilder from my unit test class. How can I do this? It's a shame it's so complicated to add a simple logger to a simple unit test class - this should be built in by default I would think.

4
  • The framework is heavily modularized so that you can customize what you need without a bunch of boilerplate bloat included where it is not needed.
    – Nkosi
    Commented Jul 16, 2019 at 17:48
  • 1
    Are you using the DI framework just to get a logging instance, or do you leverage the DI framework in tests for other reasons?
    – Matthew
    Commented Jul 17, 2019 at 16:32
  • I am using DI in the app but not in the unit tests. In the unit tests I manually inject the dependencies. Commented Jul 18, 2019 at 6:06
  • Java has logging for tests out of the box. Why C#/.NET makes it so hard?
    – wilmol
    Commented Jul 26, 2023 at 23:43

3 Answers 3

7

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.

using Xunit;
using Xunit.Abstractions;

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

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

    [Fact]
    public void FooBar()
    {
        var myClass = new MyClass(_logger);
        myClass.WizzBang();
    }
}
4
  • I am actually using mstest, but will probably switch to xunit. This is very handy information I will keep on file, thank you. Commented Jul 17, 2019 at 15:58
  • 1
    This should probably have an example of how to send a log message using XUnits logger.
    – FoxDeploy
    Commented Jun 8, 2021 at 14:58
  • 2
    @FoxDeploy not quite sure what you mean, the example shows how to get an ILogger<T> instance.
    – Matthew
    Commented Jun 8, 2021 at 15:37
  • Perfect. Prefer this over adding Console.Writeline in my code. Is there a way to add to all test classes by default?
    – wilmol
    Commented Jul 26, 2023 at 23:51
5

Following up on Matthew's answer, per the xUnit documentation in 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);
    }
}
4

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.

5
  • 1
    Thanks, exactly what I was looking for. However, now I guess I need to figure out how to set the verbosity, without having an appSettings file (since it's a unit test), because I am not seeing any of the EF logging information in the debug window. Commented Jul 17, 2019 at 15:59
  • @RandyGamage EF logging? is this a unit test or an integration test?
    – Nkosi
    Commented Jul 17, 2019 at 16:09
  • This is an integration test, as I'm actually hitting the database. It's actually part of a workshop I am developing, to show students the actual SQL generated for various simple EF linq->SQL, and show them which ops will operate in the db, and which will be evaluated locally, etc. so I wanted to show warnings and ef logging as part of the workshop. But I am only seeing those log outputs when the actual app is run, not in the UTs. Commented Jul 17, 2019 at 22:13
  • Just to clarify I also have unit tests that run against an in-memory EF database, but the requirements are the same. I want to see the logs of the generated SQL in both cases. Commented Jul 18, 2019 at 6:04
  • @RandyGamage were you able to figure out the verbosity setting?
    – LOST
    Commented Aug 23 at 19:08

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.