Search code examples
c#logging.net-6.0appsettingskestrel

How to update/reload LogLevels, configured by appsettings.json at runtime?


I am working on a .NET6 Kestrel application using appsettings.json for configuration and default console logging.

What I try to do is, that I want to change log-levels at runtime. However, so far the log-levels were only updated on restart.

Am I missing something besides reloadOnChange=true?

Here's the relevant code: Code

static void Configure(IConfigurationBuilder config)
{
  config.AddJsonFile("appsettings.json", false, true);
  config.AddEnvironmentVariables();
}
ConfigurationBuilder cb = new();
Configure(cb);
IConfigurationRoot configuration = cb.Build();
IWebHostBuilder webHost = WebHost
  .CreateDefaultBuilder(args)
  .ConfigureLogging(c =>
  {
    c.AddConfiguration(configuration);
    c.AddConsole();
  })
  .ConfigureAppConfiguration(Configure)
  .UseStartup<TStartup>();

Thank you all in advance!


Solution

  • You don't need to manually add these files because CreateDefaultBuilder already takes care of that for you.

    Additionally, when you run the app in Visual Studio, it automatically sets the "Development" environment variable (as specified in launchSettings.json). Consequently, the appsettings.development.json file will take precedence. Therefore, ensure that you are making changes in the correct file corresponding to the current environment.


    I've made a simple POC and it just works fine here, please give a try:

    Program.cs

    using Microsoft.AspNetCore;
    using Microsoft.AspNetCore.Mvc;
    
    IWebHostBuilder webHost = WebHost.CreateDefaultBuilder(args).UseStartup<Startup>();
    
    webHost.Build().Run();
    
    public class Startup
    {
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllers();
        }
    
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            app.UseRouting();
            app.UseEndpoints(endpoints => { endpoints.MapControllers(); });
        }
    }
    
    [Route("test")]
    [ApiController]
    public class TestController
    {
        private readonly ILogger<TestController> _logger;
    
        public TestController(ILogger<TestController> logger)
        {
            _logger = logger;
        }
    
        [HttpGet]
        public IActionResult Get()
        {
            _logger.LogTrace("Trace log!");
            _logger.LogDebug("Debug log!");
            _logger.LogInformation("Information log!");
            _logger.LogWarning("Warning log!");
            _logger.LogError("Error log!");
            _logger.LogCritical("Critical log!");
    
            return new OkResult();
        }
    }
    

    Changes on appsettings.json file immediately takes effect on logger output to console when calling the test endpoint.

    SettingsUpdateTest