Add, enable and disable NLog loggers programmatically

Stacker picture Stacker · Sep 19, 2011 · Viewed 15.4k times · Source

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

Answer

Jon picture Jon · Sep 19, 2011

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();