NLog: how to obtain level of a specific target programatically

Viewed 163

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 Answers

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

Related