Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NLog: how to obtain level of a specific target programatically

Tags:

c#

nlog

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?

like image 860
shelbypereira Avatar asked Nov 16 '25 17:11

shelbypereira


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

like image 71
Julian Avatar answered Nov 18 '25 07:11

Julian



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!