Search code examples
nlog

(NLog) When to call ReconfigExistingLoggers?


What types of changes require a call to ReconfigExistingLoggers?

In my particular use case, I load everything from a config file and then:

  1. Delete a Target
  2. Delete a rule that would have logged to the target

This seems to work without me calling ReconfigExistingLoggers, but I wanted to be sure I wasn't missing anything.

Additionally, I'm considering a refactor that would use a variable. This means I would have a Target that uses a variable and a single rule that logs to that Target. At runtime, I would set/update that variable.

Does that require a call to ReconfigExistingLoggers?

My specific use case is around the Syslog target:

When my software starts up, it needs to decide whether to log to SyslogServerA or SyslogServerB. My current approach is:

  1. Configure both servers in my Config file
  2. Configure rules to log to both servers in my Config file
  3. At startup, determine the server I should log to
  4. Remove the Target and Rule for the other one

I can think of several ways to achieve my end goal of only logging to a single syslog server, but I'm not sure which way is best.

For what it's worth: If I have both Targets and both Rules active, I have a runaway memory problem that builds over time. This is why I'm actively disabling an unused UDP Syslog target.


Solution

  • The LogManager.ReconfigExistingLoggers() should be explicitly called after having added/updated/removed LoggingRules (Like a commit-operation). It will refresh the configuration of all active Logger-objects. It will also perform synchronous initialization of any new NLog targets, so when the call has completed then all changes has been applied.

    NLog has the following method to remove existing target from a configuration:

    NLog supports changes of LoggingConfiguration while application is running (Ex. adding removing LoggingRules and Targets). But it is recommended to register all NLog targets upfront, and then use semi-dynamic-filtering to enable/disable output to the relevant NLog targets (Notice minLevel="Off" means disable output to target)