Using NLog LogLevel value from AppSettings configuration file

1.3k Views Asked by At

I need to configure NLog settings from another application, essentially I have a main Application and a Configuration Application and need to set some log settings from the Configuration Application.

I have tried below but minlevel is an enum and is not valid.. :(

<logger name="*" minlevel="${appsetting:MinimumLogLevel}" writeTo="File" />

It would be perfect for this to work, any suggestions?

Thanks

1

There are 1 best solutions below

0
On BEST ANSWER

** Updated Answer **

NLog ver. 4.6 added support for using NLog-Config-Variables in minLevel. See https://github.com/NLog/NLog/pull/2709

NLog ver. 4.6.7 added support for adjusting minLevel at runtime, by modifying NLog-Config-Variables and calling ReconfigExistingLoggers(). See https://github.com/NLog/NLog/pull/3184

** Original Answer **

the minlevel attribute is indeed not a Layout, so you can't use layout renderers like `${appsetting}.

You could do it programmatically:

var configuration = LogManager.Configuration;

//TODO find correct rule
var rule = configuration.LoggingRules[0];

//disable all
rule.DisableLoggingForLevel(LogLevel.Trace);
rule.DisableLoggingForLevel(LogLevel.Debug);
rule.DisableLoggingForLevel(LogLevel.Trace);
rule.DisableLoggingForLevel(LogLevel.Info);
rule.DisableLoggingForLevel(LogLevel.Warn);
rule.DisableLoggingForLevel(LogLevel.Error);
rule.DisableLoggingForLevel(LogLevel.Fatal);


var minLevelRaw = System.Configuration.ConfigurationManager.AppSettings["minLevel"];
var minLevel = LogLevel.FromString(minLevelRaw);

//enable correct one
rule.EnableLoggingForLevels(minLevel, LogLevel.Fatal); //enable from minLevel to fatal

LogManager.Configuration = configuration;

or if it should work for all rules, you could use GlobalThreshold:

var minLevelRaw = System.Configuration.ConfigurationManager.AppSettings["minLevel"];
var minLevel = LogLevel.FromString(minLevelRaw);

LogManager.GlobalThreshold = minLevel;