【问题标题】:How to log to multiple targets using NLog?如何使用 NLog 记录到多个目标?
【发布时间】:2011-03-18 06:58:35
【问题描述】:

我正在使用 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");

【问题讨论】:

    标签: c# logging configuration nlog


    【解决方案1】:

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

    【讨论】:

    • 这种方式仍然会覆盖规则,将您限制在一个规则中。杰森的回答对我来说似乎更正确。
    【解决方案2】:

    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 ();
    

    【讨论】:

    • LogManager.Configuration.Reload() 对我不起作用;没有任何记录。起作用的是声明一个新变量var config = new LoggingConfiguration();,在config 上执行上述步骤,然后设置LogManager.Configuration = config;Reload 不适用于 Nlog 2.0.0.0。
    猜你喜欢
    • 2011-12-16
    • 1970-01-01
    • 2016-05-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-12
    • 2012-10-26
    • 1970-01-01
    相关资源
    最近更新 更多