Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 992
Randy Gamage Avatar asked Jul 16 '19 17:07

Randy Gamage


People also ask

How do I enable debug logging?

Navigate to Event Viewer (Local)\Applications and Service Logs\Microsoft\User Experience Virtualization\App Agent. Right-click on Debug under App Agent and select Enable Log. Select OK when presented with the "Analytic and Debug logs may lose events when they are enabled.

How do I debug C in Visual Studio?

To do that, open C++ file in VSCode and either hit F5 or go to Debug -> Start Debugging and select C++ (GDB/LLDB) then select g++.exe build and debug active file . Notice that I've added one more optional configuration g++ build & run active file in launch. json and g++ build & run in tasks.


1 Answers

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.

like image 56
Nkosi Avatar answered Oct 28 '22 01:10

Nkosi