Add, enable and disable NLog loggers programmatically

老子叫甜甜 提交于 2019-11-30 08:25:59

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();
Duke of Muppets

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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!