Tuesday, February 21, 2023

Logging the configuration changes in .Net Web API applications

The traditional .Net Framework web applications hosted in IIS will restart automatically when the configuration changes. The configuration is mainly stored in web.config and the restart will be performed by the IIS by watching the files. .Net Core and continuing .Net has the same feature to monitor the config changes and get it reflected in the application. At least in .Net the application will not be entirely restarting but the values will be available to consumers of IConfigration.

Problem

Ideally, if the consumer class of IConfiguration is not caching the values, they all get the updated values. But in large applications, there may be chances that some classes may be caching the values into member variables. Then upon config change, some classes work properly some do not. Eventually, this led to bug and production war rooms.

Having proper code reviews educate developers etc...is the solution to the problem. But as a debugger how to identify that a config changed in between which was the potential reason for the subsequent defect?

Solution

Ideally, there should be the below section in the config that logs the configuration changes.
  
"Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning",
      "Microsoft.Extensions.Configuration": "Debug"
    }
  },
But it's not working. So what next?

Subscribe to changes and log ourselves. The code is as follows.
            var builder = WebApplication.CreateBuilder(args);
            builder.Services.AddControllers();
            builder.Services.AddEndpointsApiExplorer();
            builder.Services.AddSwaggerGen();
            var app = builder.Build();

            // Adding the change detection
            ChangeToken.OnChange(
                app.Configuration.GetReloadToken,
                () => app.Logger.LogWarning("Configuration changed"));
It is simple to change but a little different than we expect in the .Net Core programming model. It uses the ChangeToken class to get the changes.

Happy debugging...

No comments: