简体   繁体   English

如何告诉NLog有选择地登录到两个不同的内存目标?

[英]How can I tell NLog to selectively log to two different memory targets?

I have a class with an NLog MemoryTarget. 我有一个带有NLog MemoryTarget的类。 I have the need for each instance of the class that the logs from that instance goes to its MemoryTarget aggregated instance. 我需要该类的日志的每个实例都进入其MemoryTarget聚合实例。

I use SimpleConfigurator.ConfigureForTargetLogging(instance.MemoryTarget, LogLevel.Trace) to initialise the logger, which causes the last ConfigureForTargetLogging call on the last instance to direct all logging to the last instance's MemoryTarget. 我使用SimpleConfigurator.ConfigureForTargetLogging(instance.MemoryTarget,LogLevel.Trace)初始化记录器,这导致对最后一个实例的最后一次ConfigureForTargetLogging调用将所有日志记录定向到最后一个实例的MemoryTarget。

The MemoryTarget can be instantiated with a name, but I'm not sure I have a way to create a logger instance that sends to that named target only. 可以使用名称实例化MemoryTarget,但是我不确定我是否有办法创建仅发送到该命名目标的logger实例。

You can use logger name filters in rules: Do not forger final keyword that quit processing any further rule when this one matches: 您可以在规则中使用记录器名称过滤器:当此关键字匹配时,请勿伪造终止处理任何其他规则的final关键字:

<?xml version="1.0" encoding="utf-8" ?>
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">

  <targets>
    <target name="perf" xsi:type="File" fileName="perf.log" />
    <target name="console" xsi:type="Console" />
  </targets>

  <rules>
    <logger name="Perf" minlevel="Info" writeTo="perf.log" final="true" />
    <logger name="*" minlevel="Debug" writeTo="console" />
  </rules>
</nlog>

Programmatically: 以编程方式:

var config = new NLog.Config.LoggingConfiguration();

var logfile = new NLog.Targets.FileTarget() { FileName = "perf.log", Name = "perf" };
var console = new NLog.Targets.ConsoleTarget() { Name = "console" };

config.LoggingRules.Add(new NLog.Config.LoggingRule("Perf", LogLevel.Info, perf)){Final="true"};
config.LoggingRules.Add(new NLog.Config.LoggingRule("*", LogLevel.Debug, console));

NLog.LogManager.Configuration = config;

in your code you can get named logger: 在您的代码中,您可以命名为logger:

Logger logger = NLog.LogManager.GetLogger("Perf")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM