Search code examples
logging.net-coreasp.net-core-hosted-services

.NET Core Hosted Service Logging LogLevel in Environment Variable


I created a hosted service with the following code:

class Program
    {
        static async Task Main(string[] args)
        {

            await new HostBuilder()
                .ConfigureAppConfiguration((hostContext, configApp) =>
                    {
                        configApp.AddEnvironmentVariables(prefix: "SAMPLEHOST_");
                        configApp.AddCommandLine(args);
                    })
                .ConfigureServices((hostContext, services) =>
                    {
                        services.AddHostedService<SampleHostedService>();
                        services.AddHostedService<AnotherHostedService>();
                    })
                .ConfigureLogging((hostingContext, logging) => 
                    {
                        logging.AddConsole();
                    })
                .RunConsoleAsync();
        }
    }

...having the following launchsettings.json.

{
  "profiles": {
    "SampleHost.Cli": {
      "environmentVariables": {
        "LOGGING__LOGLEVEL__DEFAULT": "Debug",
      }
    }
  }
}

I can't seem to make this appear in my console. :(

Logger.LogDebug("Hello debug");

I want modify and tweak the LogLevel purely on environment variable. Did I missed anything?


Solution

  • You probably need something like this:

    .ConfigureLogging((hostingContext, logging) => 
    {
        logging.AddConfiguration(hostingContext.Configuration.GetSection("Logging"));
        logging.AddConsole();
    })