我有两个同时存在于同一进程中的SharePoint计时器作业。这些工作彼此无关,并且不能共享NLog配置。但是,它们往往会相互重叠,并记录每个其他文件。
所有配置均由代码完成。命名目标并命名记录器。我确保获得当前LogManager.Configuration的引用并重新加载它。
第一个计时器作业中的配置:
if (LogManager.Configuration == null)
{
LogManager.Configuration = new LoggingConfiguration();
}
var fileTarget = new FileTarget();
LogManager.Configuration.AddTarget("file", fileTarget);
fileTarget.Encoding = Encoding.UTF8;
fileTarget.FileName = "C:/OTDPLog/Log-{0}.txt"._Format(DateTime.Now.ToString("dd-MM-yyyy_hhmmss"));
fileTarget.Layout = "${date:format=HH\\:mm\\:ss} ${logger} ${event-context:item=Dev} [${level:uppercase=true}]\t${message}. ${exception:format=ToString,StackTrace}";
var async = new AsyncTargetWrapper(fileTarget, 5000, AsyncTargetWrapperOverflowAction.Block);
var rule = new LoggingRule("OTDP", LogLevel.Debug, async);
LogManager.Configuration.LoggingRules.Add(rule);
LogManager.Configuration.Reload();
用法:
var logger = LogManager.GetLogger("OTDP");
logger.Info("bla bla bla");
其他工作的配置:
if (LogManager.Configuration == null)
{
LogManager.Configuration = new LoggingConfiguration();
}
var fileTarget = new FileTarget();
LogManager.Configuration.AddTarget("file", fileTarget);
fileTarget.Encoding = Encoding.UTF8;
fileTarget.FileName = "C:/WikiLog/Log-{0}.txt"._Format(DateTime.Now.ToString("dd-MM-yyyy_hhmmss"));
fileTarget.Layout = "${date:format=HH\\:mm\\:ss} ${logger} ${event-context:item=Dev} [${level:uppercase=true}]\t${message}. ${exception:format=ToString,StackTrace}";
var async = new AsyncTargetWrapper(fileTarget, 5000, AsyncTargetWrapperOverflowAction.Block);
var rule = new LoggingRule("Wiki", LogLevel.Debug, async);
LogManager.Configuration.LoggingRules.Add(rule);
LogManager.Configuration.Reload();
用法:
var logger = LogManager.GetLogger("Wiki");
logger.Info("bla bla bla");
如何在同一过程中为不同的应用程序设置记录器?
答案 0 :(得分:5)
所以我终于找到了解决方案。首先,当配置NLog直接在LogManager.Configuration上工作时,我不可能获得一个引用,对该引用做我的工作,最后设置LogManager.Configuration。其次,我必须重命名目标,他们都被命名为“文件”,他们必须有不同的名称。
if (LogManager.Configuration == null)
{
LogManager.Configuration = new LoggingConfiguration();
}
var config = LogManager.Configuration;
// Do my stuff, add targets and rules...
LogManager.Configuration = config;