13

我正在使用 NLog,我想同时登录到 RichTextBox 和 File。我想以编程方式配置 Logger,而不是使用 xml 配置文件。

以下代码仅记录到最后一个目标(在本例中为文件)。有人可以帮忙吗?

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");
4

2 回答 2

9

好的,我明白了。在发布问题之前,我应该更多地阅读帮助文件。但无论如何,答案是使用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");
于 2010-07-20T07:39:40.380 回答
7

SimpleConfigurator 会覆盖所有现有规则。在您的示例中,您有 2 个调用,因此第一个目标被丢弃。

相反,您应该手动添加目标和日志记录规则并调用 Reload():

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 ();
于 2012-07-03T08:45:06.663 回答