我正在使用NLog,我想同时登录RichTextBox和File。我想以编程方式配置Logger,而不是使用xml配置文件。
以下代码仅记录到最后一个目标(在本例中为File)。有人可以帮忙吗?
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");
答案 0 :(得分: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");
答案 1 :(得分: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 ();