How can I add, edit, delete, enable, and disable loggers from code for NLog?
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();
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:
来源:https://stackoverflow.com/questions/7471490/add-enable-and-disable-nlog-loggers-programmatically