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.
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:
Can you guess why does this work ? Let me know your thoughts.