Multiple Ways To Set MInimum Log Level in .NET Applications

Multiple Ways To Set MInimum Log Level in .NET Applications

In some recent posts, we have been discussing about .NET logging. We have seen how configurations can be set and how do they affect which log message would be stored in the logging storage medium. This is decided by the minimum log level.

In one of the recent posts we have seen that minimum log level can be specified in appsettings.json configurations. In this post, let’s have a quick look at couple of other ways to set the minimum log level.

Code

IHostBuilder has a method ConfigureLogging, which takes an Action parameter. This Action expects HostBuilderContext and ILoggingBuilder parameters. ILoggingBuilder provides a method SetMinimumLevel, which can be used to set the minimum log level via Code.

Note that documentation recommends to use configurations for setting minimum log level so that they can be changed quickly, without modifying the code.

class Program
{
static Task Main(string[] args)
{
var host = CreateHostBuilder(args).Build();
var workerInstance = host.Services.GetRequiredService<Worker>();
workerInstance.Execute();
return host.RunAsync();
}
static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureServices((_, services) =>
{
services.AddTransient<Worker>();
})
.ConfigureLogging((_, logging) =>
{
logging.SetMinimumLevel(LogLevel.Debug);
logging.ClearProviders();
logging.AddSimpleConsole(options => options.IncludeScopes = true);
logging.AddEventLog();
});
}
view raw Program.cs hosted with ❤ by GitHub

Commands

Let’s consider that an application has an appsettings.json file, which has below logging configuration.

"Logging": {
"Console": {
"LogLevel": {
"Microsoft": "Trace"
}
}
}
view raw appsettings.json5 hosted with ❤ by GitHub

When these settings are loaded by application, the key value pair collection contains all tokens separated by ‘:’ character i.e. Logging:Console:LogLevel:Microsoft.

If required, the minimum log level can be set either via command line. Whole key needs to be specified in the command. But instead of ‘:’ characters, use double underscores to combine the tokens. So it would become Logging__Console__LogLevel__Microsoft.

Then command line can be used to set this value as shown in below code:

## This command is to set the environment variable temporarily
## Sets variable for only current window
## Hence, not applicable if app is run from Visual Studio
set Logging__LogLevel__Microsoft=Information
dotnet run
## Setx to persist the setting in environment variables
## The swtich /M is to set the variable at system level
## Without this switch, variable is set at user level
## If SETX is used, apps run from Visual Studio would also use this value.
setx Logging__LogLevel__Microsoft=Information /M
dotnet run
view raw commands.sh hosted with ❤ by GitHub

Can you guess why does this work ? Let me know your thoughts.

Leave a Reply