C# 如何使用NLog登录到多个目标?
我正在使用NLog,我想同时登录到RichTextBox和文件。我希望以编程方式配置记录器,而不是使用xml配置文件 以下代码只记录到最后一个目标(本例中为文件)。有人能帮忙吗C# 如何使用NLog登录到多个目标?,c#,logging,configuration,nlog,C#,Logging,Configuration,Nlog,我正在使用NLog,我想同时登录到RichTextBox和文件。我希望以编程方式配置记录器,而不是使用xml配置文件 以下代码只记录到最后一个目标(本例中为文件)。有人能帮忙吗 RichTextBoxTarget t1 = new RichTextBoxTarget(); t1.Layout = "${date} ${message}"; t1.ControlName = "rtb_log"; t1.FormName = "MainForm"; NLog.Config.SimpleConfigu
RichTextBoxTarget t1 = new RichTextBoxTarget();
t1.Layout = "${date} ${message}";
t1.ControlName = "rtb_log";
t1.FormName = "MainForm";
NLog.Config.SimpleConfigurator.ConfigureForTargetLogging(t1, LogLevel.Debug);
FileTarget t2 = new FileTarget();
t2.Layout = "${date} ${level} ${message}";
t2.FileName = "${basedir}/Logs/today.log";
t2.KeepFileOpen = false;
t2.Encoding = "iso-8859-2";
NLog.Config.SimpleConfigurator.ConfigureForTargetLogging(t2, LogLevel.Trace);
Logger logger = LogManager.GetLogger("MyLogger");
好的,我知道了。在发布问题之前,我应该仔细阅读帮助文件。但无论如何,答案是使用
SplitTarget
,如下所示
RichTextBoxTarget t1 = new RichTextBoxTarget();
t1.Layout = "${date} ${message}";
t1.ControlName = "rtb_log";
t1.FormName = "MainForm";
FileTarget t2 = new FileTarget();
t2.Layout = "${date} ${level} ${message}";
t2.FileName = "${basedir}/Logs/today.log";
t2.KeepFileOpen = false;
t2.Encoding = "iso-8859-2";
SplitTarget target = new SplitTarget();
target.Targets.Add(t1);
target.Targets.Add(t2);
NLog.Config.SimpleConfigurator.ConfigureForTargetLogging(target, LogLevel.Debug);
Logger logger = LogManager.GetLogger("MyLogger");
SimpleConfigurator覆盖所有现有规则。在您的示例中,您有2个调用,因此第一个目标被丢弃 相反,您应该手动添加目标和日志规则,并调用Reload():
这种方式仍然会覆盖规则,将您限制为一个规则。Jason的回答对我来说似乎更正确。
LogManager.Configuration.Reload()
对我不起作用;没有记录任何内容。工作原理是声明一个新变量var config=new LoggingConfiguration()
,在config
上执行上述步骤,然后设置LogManager.Configuration=config代码>。使用Nlog 2.0.0.0时,重新加载
不起作用。
LogManager.Configuration.AddTarget (t1);
LogManager.Configuration.AddTarget (t2);
LoggingRule r1 = new LoggingRule ("*", LogLevel.Debug, t1);
LoggingRule r2 = new LoggingRule ("*", LogLevel.Trace, t2);
LogManager.Configuration.LoggingRules.Add (r1);
LogManager.Configuration.LoggingRules.Add (r2);
LogManager.Configuration.Reload ();