How to get an ILogger in Main() before calling builder.Build()

654 views Asked by At

I followed the guidance here and here. And what I came up with is:

    var configuration = new ConfigurationBuilder()
            .AddEnvironmentVariables()
            .AddJsonFile($"appsettings.{Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT")}.json",
            true, true)
            .Build();
        using (var loggerFactory = LoggerFactory.Create(loggingBuilder => loggingBuilder
                   .AddConfiguration(configuration)))
        {
            logger = loggerFactory.CreateLogger<Program>();
        }

That gave me a valid ILogger - that generated no logs. I did look at the configuration object and it did have all the settings from my appsettings.development.json.

So I then did the following:

        using (var loggerFactory = LoggerFactory.Create(loggingBuilder => loggingBuilder
                   .AddConfiguration(configuration.GetSection("Logging"))
                   .AddJsonConsole()
                   .AddDebug()))
        {
            logger = loggerFactory.CreateLogger<Program>();
        }

And this works. Without the .GetSection("Logging") it only displayed logs of Warning and greater. Without the AddJsonConsole() and AddDebug() it displayed nothing.

So... why? I have it working and that's great, but I'd like to know why it doesn't build from the config?

2

There are 2 answers

0
Neil W On BEST ANSWER

The config in appsettings is just setting value to be used with the logging system.

However, you still require AddJsonConsole and AddDebug to actually add the providers to the logging system. The configuration in appsettings will then configure those.

The configuration without explicitly adding the providers will render the configuration redundant.

1
Ruikai Feng On

Here's the document related:

The default ASP.NET Core web app templates:

Use the Generic Host. Call WebApplication.CreateBuilder, which adds the following logging providers:

Console

Debug

EventSource

EventLog: Windows only

You could also check the codes in WebApplicationBuilder

services.AddLogging(logging =>
        {
            logging.AddConfiguration(configuration.GetSection("Logging"));
            logging.AddSimpleConsole();

            logging.Configure(options =>
            {
                options.ActivityTrackingOptions =
                    ActivityTrackingOptions.SpanId |
                    ActivityTrackingOptions.TraceId |
                    ActivityTrackingOptions.ParentId;
            });
        });

It has already did what you have to do for you ,when you create Ilogger through Iloggerfactory ,you have to set the provider and configuration yourself