【问题标题】:How to log to multiple targets with different logging levels using NLog?如何使用 NLog 记录到具有不同日志记录级别的多个目标?
【发布时间】:2011-12-16 12:21:29
【问题描述】:

我遇到了那里描述的相同问题: Another StackOverflow Question

我需要记录到文件和方法调用。 问题是有很多“调试”级别的日志消息更详细。 我需要他们登录到文件。但该方法应该只接收调试级别以上的日志消息。

因此,SplitGroupTarget 不能满足我的要求。 这个问题有什么解决方案或变通方法吗?

另外,我在 2006 年在 NLog 论坛中发现了这个条目,但也有类似的问题 - 但还没有答案:NLog Forum

EDIT1:我忘了提到我想以编程方式配置它。 根据您的回答,我尝试了以下方式,但只记录了最后一个目标。

SimpleConfigurator.ConfigureForTargetLogging(methodCallTarget, LogLevel.Debug);
SimpleConfigurator.ConfigureForTargetLogging(fileTarget, LogLevel.Debug);

【问题讨论】:

    标签: logging target nlog


    【解决方案1】:

    我刚刚找到了以编程方式记录多个目标的解决方案。

    我只是不使用SimpleConfigurator,而是使用LogManagerNLog.LoggingConfiguration 设置为其属性。

    所以我得到了以下代码 sn-p:

    // define the targets
    // ......
    
    // create configuration object and set previously created targets
    LoggingConfiguration configuration = new LoggingConfiguration();
    configuration.AddTarget("methodCall", methodCallTarget);
    configuration.AddTarget("logfile", fileTarget);
    
    // create logging rules where i can specify the minimum log levels
    // and add them to the configuration objects LoggingRules Enumerable.
    LoggingRule logFileRule = new LoggingRule("*", NLog.LogLevel.Debug, fileTarget);
    configuration.LoggingRules.Add(logFileRule);
    
    LoggingRule methodCallRule = new LoggingRule("*", NLog.LogLevel.Info, methodCallTarget);
    configuration.LoggingRules.Add(methodCallRule);
    
    // Finally set the configuration object to the LogManagers Configuration property
    LogManager.Configuration = configuration;
    

    感谢您的回答!

    【讨论】:

      【解决方案2】:

      您应该能够指定相同的记录器并将其发送到两个不同的目标。

      假设您为文件配置了目标"f1",为方法配置了"m1",您应该可以像这样配置记录器:

      <logger name="*" minlevel="Trace" writeTo="f1" />  
      <logger name="*" minlevel="Debug" writeTo="m1" />  
      

      这应该将所有日志消息发送到文件目标f1,并将所有调试和更高级别的消息发送到方法目标m1

      另外,请参阅question and its answers,了解有关配置 NLog 的更多信息。您可能会发现一些有用的东西。

      我刚刚在 Google 上搜索了一下,发现这篇文章似乎描述了您的问题和解决方案:

      http://nlog-forum.1685105.n2.nabble.com/Programatic-Configuration-of-targets-and-rules-td1685349.html

      也许会有所帮助。

      【讨论】:

      • 感谢您的回复,但我尝试以编程方式执行此操作,这种方式也不起作用。 (见我的编辑)
      【解决方案3】:

      SimpleConfigurator 会覆盖所有现有规则。在您的示例中,您有 2 个调用,因此第一个目标被丢弃。相反,您应该manually add a target and logging rule

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-03-18
        • 2012-05-24
        • 1970-01-01
        • 2015-03-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-03-26
        相关资源
        最近更新 更多