5
votes

I have a console app that will use DI to supply configuration (Options Pattern), logging and other service references to services within the app.

I have a problem in that logging is working for Info/Warning/Error/Critical but Debug and Trace are not showing up. I have set the console level to Trace. If I just create a logger factory, all logs are shown.

It sounds like it is using defaults. For loggers created in the DI service collection, is there another way to configure the log level?

I have tried adding a dispose on the service collection as referred to in this post, Edit 2 link and no luck.

using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Console;
using System;

namespace DownloadClientData.App
{
    class Program
    {
        static int Main(string[] args)
        {
            //***if I use this way to create the logger in the DI container, debug and trace messages are not displayed
            var serviceCollection = new ServiceCollection();
            serviceCollection.AddLogging();

            //tried this alternative too - no change...
            //serviceCollection.AddLogging(LoggingBuilder => LoggingBuilder.AddFilter<ConsoleLoggerProvider>("All Categories", LogLevel.Trace));
            var serviceProvider = serviceCollection.BuildServiceProvider();
            var loggerFactory = serviceProvider.GetService<ILoggerFactory>();

            //***If I comment out the above lines and uncomment the below line, all 6 logs are displayed.

            //var loggerFactory = new LoggerFactory();
            loggerFactory
                .AddConsole(LogLevel.Trace)
                .AddDebug(LogLevel.Trace);

            var logger = loggerFactory.CreateLogger(typeof(Program));
            logger.LogInformation("Information");
            logger.LogTrace("Trace");
            logger.LogDebug("Debug");
            logger.LogWarning("Warning");
            logger.LogCritical("Critical");
            logger.LogError("Error");
            Console.ReadKey();
            return 0;

            }
    }

}

1

1 Answers

5
votes

The defaults for the minimum log level are different when using the AddLogging() extension method on ServiceCollection. You can set it like this:

static void Main(string[] args)
{
    var serviceCollection = new ServiceCollection()
        .AddLogging(builder => {
            builder.SetMinimumLevel(LogLevel.Trace);
            builder.AddConsole();
            builder.AddDebug();
        });

    var serviceProvider = serviceCollection.BuildServiceProvider();
    var loggerFactory = serviceProvider.GetService<ILoggerFactory>();

    var logger = loggerFactory.CreateLogger(typeof(Program));
    logger.LogInformation("Information");
    logger.LogTrace("Trace");
    logger.LogDebug("Debug");
    logger.LogWarning("Warning");
    logger.LogCritical("Critical");
    logger.LogError("Error");
    Console.ReadKey();
}