如何使用NLog登录多个目标?

Imr*_* S. 13 c# configuration logging nlog

我正在使用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");
Run Code Online (Sandbox Code Playgroud)

Imr*_* S. 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");
Run Code Online (Sandbox Code Playgroud)


maf*_*afu 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 ();
Run Code Online (Sandbox Code Playgroud)

  • `LogManager.Configuration.Reload()` 对我不起作用;没有记录任何内容。有效的方法是声明一个新变量 `var config = new LoggingConfiguration();`,对 `config` 执行上述步骤,然后设置 `LogManager.Configuration = config;`。“重新加载”在 Nlog 2.0.0.0 中不起作用。 (2认同)