3
votes

I currently use NLog and allow admin users to set the level at runtime using a variable as follows:

<logger name="*" minLevel="${var:myFileLevel}" writeTo="file" />

I would like to know the level of this logger at runtime (so I cannot obtain it from the configuration file due to the variable)

I am able to easily obtain the Target as follows:

Target target= LogManager.Configuration.FindTargetByName("file");

but unfortunately there are no relevant methods on the target object to obtain the level. Is it possible to obtain the logging level at runtime?

1
Why don't check Logger.IsEnabled(logLevel) or particular Logger.Is*Enabled properties? This allows you to be sure in what's configured for any given logger.Dennis
@Dennis : I tried that but it fails if you have multiple targets configured at different levels. Accepted solution is exactly what I need.shelbypereira

1 Answers

3
votes

The enabled logging level is configured at the logging rule.

So you could do this:

  1. Add a rulename, so you could find the rule easier:

    <logger name="*" minLevel="${var:myFileLevel}" writeTo="file" ruleName="myrule" />
    
  2. Find the rule and check the Levels property. See LoggingConfiguration.FindRuleByName Method

    var rule = LogManager.Configuration.FindRuleByName("myrule");
    var levels = rule.Levels;  // enabled levels
    

For this case, another option is to read the myFileLevel variable value. For that, you need to render it, you could use LogEventInfo.CreateNullEvent() for that.

var myFileLevelLayout = LoggingConfiguration.Variables["myFileLevel"]; // Type SimpleLayout
string value = myFileLevelLayout.Render(LogEventInfo.CreateNullEvent())

See
LoggingConfiguration.Variables Property