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.
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.
|static Task Main(string args)|
|var host = CreateHostBuilder(args).Build();|
|var workerInstance = host.Services.GetRequiredService<Worker>();|
|static IHostBuilder CreateHostBuilder(string args) =>|
|.ConfigureServices((_, services) =>|
|.ConfigureLogging((_, logging) =>|
|logging.AddSimpleConsole(options => options.IncludeScopes = true);|
Let’s consider that an application has an
appsettings.json file, which has below logging configuration.
When these settings are loaded by application, the key value pair collection contains all tokens separated by ‘:’ character i.e.
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
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|
|## 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|
Can you guess why does this work ? Let me know your thoughts.