Debug
. It may be enough to localize the bug but sometimes it isn’t. Even if you are allowed to restart the app in production with lower log level, the issue may go away … temporarily, i.e. the app still has a bug.
Better solution is to change the log level temporarily without restarting the app.
First step is to initialize the logger with the IConfiguration
. That way the logger changes the level as soon as you change the corresponding configuration (file).
In this post I will provide 2 examples, one that is using the ILoggingBuilder
of the ASP.NET Core and the other example is using Serilog because it is not tightly coupled to ASP.NET Core (but works very well with it!).
Using ILoggingBuilder
:
// the content of appsettings.json
{
"Logging": {
"LogLevel": { "Default": "Information" }
}
}
-----------------------------------------
var config = new ConfigurationBuilder().
AddJsonFile("appsettings.json", false, true) // reloadOnChange=true
.Build();
// Setup of ASP.NET Core application
WebHostWebHost
.CreateDefaultBuilder()
.ConfigureLogging(builder =>
{
builder.AddConfiguration(config); // <= init logger
builder.AddConsole();
})
...
Using Serilog:
// the content of appsettings.json
{
"Serilog": {
"MinimumLevel": { "Default": "Information" }
}
}
-----------------------------------------
var config = new ConfigurationBuilder()
.AddJsonFile("appsettings.json", false, true) // reloadOnChange=true
.Build();
var serilogConfig = new LoggerConfiguration()
.ReadFrom.Configuration(config) // <= init logger
.WriteTo.Console();
In case you are interested in integration with (ASP).NET Core
// If having a WebHost
WebHost
.CreateDefaultBuilder()
.ConfigureLogging(builder =>
{
builder.AddSerilog(serilogConfig.CreateLogger());
})
...;
// If there is no WebHost
var loggerFactory = new LoggerFactory()
.AddSerilog(serilogConfig.CreateLogger());
At this point the loggers are coupled to IConfiguration
or rather to appsettings.json
, i.e if you change the level to Debug
the app starts emitting debug-messages as well, without restarting it.
This solution has one downside, you need physical access to the appsettings.json
. Even if you do, it still would be better to not change the configuration file. What we want is a component that let us set and reset a temporary log level
and if this temporary level is not active then the values from appsettings.json
should be used. That way you can change the level from the GUI or via an HTTP request against the Web API of your web application.
Luckily, the implementation effort for that feature is pretty low, but that’s for another day…