Stacker
Stacker

Reputation: 8237

Add, enable and disable NLog loggers programmatically

How can I add, edit, delete, enable, and disable loggers from code for NLog?

Upvotes: 24

Views: 21538

Answers (3)

Rolf Kristensen
Rolf Kristensen

Reputation: 19847

NLog 4.6.7 makes it possible to assign Layout-variables to LoggingRule-levels, and change these Layout-variables at runtime.

<nlog>
    <variable name="myLevel" value="Warn" />
    <rules>
      <logger minLevel="${var:myLevel}" />
    </rules>
</nlog>

Then you can do this in code:

LogManager.Configuration.Variables["myLevel"] = "Debug";
LogManager.ReconfigExistingLoggers();

See also: https://github.com/NLog/NLog/wiki/Filtering-log-messages#semi-dynamic-routing-rules

Upvotes: 3

Neil Bostrom
Neil Bostrom

Reputation: 2339

I know this is an old answer but I wanted give feedback for anyone looking to make modifications to their targets and logging rules programmatically that Configuration.Reload() doesn't work.

To update existing targets programmatically you need to use the ReconfigExistingLoggers method:

var target = (FileTarget)LogManager.Configuration.FindTargetByName("logfile");
target.FileName = "${logDirectory}/file2.txt";
LogManager.ReconfigExistingLoggers();

An example that adds and removes logging rules on the fly:

if (VerboseLogging && !LogManager.Configuration.LoggingRules.Contains(VerboseLoggingRule))
{
    LogManager.Configuration.LoggingRules.Add(VerboseLoggingRule);
    LogManager.ReconfigExistingLoggers();
}
else if (!VerboseLogging && LogManager.Configuration.LoggingRules.Contains(VerboseLoggingRule))
{
    LogManager.Configuration.LoggingRules.Remove(VerboseLoggingRule);
    LogManager.ReconfigExistingLoggers();
}

As written in docs:

Loops through all loggers previously returned by GetLogger. and recalculates their target and filter list. Useful after modifying the configuration programmatically to ensure that all loggers have been properly configured.

This answer and sample comes from Tony's answer in:

Update NLog target filename at runtime

Upvotes: 15

Jon
Jon

Reputation: 437336

To add:

var logTarget = new ...
logTarget.Layout = "Your layout format here";
// e.g. "${logger}: ${message} ${exception:format=tostring}";

// specify what gets logged to the above target
var loggingRule = new LoggingRule("*", LogLevel.Debug, logTarget);

// add target and rule to configuration
LogManager.Configuration.AddTarget("targetName", logTarget);
LogManager.Configuration.LoggingRules.Add(loggingRule);
LogManager.Configuration.Reload();

Removal is done with

LogManager.Configuration.LoggingRules.Remove(loggingRule);
LogManager.Configuration.Reload();

Upvotes: 36

Related Questions