似乎有很多关于如何在出现异常时记录额外信息的信息和文档,但是我在尝试解决如何创建一个本质上是异常蜜 jar 的目标时遇到了麻烦。与其筛选各种日志文件以查看是否记录了任何异常,我只想将所有异常的副本转到写入 exceptions.log 文件的特定目标。
我该怎么做呢?
最佳答案
我不能说我真的尝试过这个,但你也许可以使用 when filter和一个 condition达到你想要的。
以下是来自 condition
的示例页:
<rules>
<logger name="*" writeTo="file">
<filters>
<when condition="length(message) > 100" action="Ignore" />
<when condition="equals('${logger}','MyApps.SomeClass')" action="Ignore" />
<when condition="(level >= LogLevel.Debug and contains(message,'PleaseDontLogThis')) or level==LogLevel.Warn" action="Ignore" />
<when condition="not starts-with('${message}','PleaseLogThis')" action="Ignore" />
</filters>
</logger>
</rules>
为了实现您的目标,您可以创建一个 filter
像这样:<rules>
<logger name="*" writeTo="file">
<filters>
<when condition="length('${exception}') > 0" action="Log" />
</filters>
</logger>
</rules>
这个想法是,如果异常字符串的长度大于 0,您只想记录消息。一些 when condition
示例使用了 NLog LayoutRenderer 语法(例如 ${message}
),有些没有(例如 message
)。我不确定哪个是正确的,或者在哪种情况下使用哪种语法。我上面直接发布的示例可能会导致仅在存在异常时才记录消息。您还应该能够进行配置,以便“正常”记录发送到一个目标的消息,并且仅在出现异常时才记录发送到“ExceptionHoneypotTarget”的消息。也许是这样的:
<rules>
<logger name="*" writeTo="ExceptionHoneypot">
<filters>
<when condition="length('${exception}') > 0" action="Log" />
</filters>
</logger>
<logger name="*" writeTo="file">
</logger>
</rules>
正如我之前提到的,我实际上还没有尝试过任何这些,但看起来你应该能够做到,希望与上面显示的类似。或者,您可以使用 FilteringWrapper围绕你的 HoneypotTarget。配置可能如下所示:
<?xml version="1.0" ?>
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<targets>
<target name="Honeypot" xsi:type="FilteringWrapper"
condition="length('${exception}')>0">
<target xsi:type="File" fileName="${basedir}/Honeypot.txt" />
</target>
<target name="normal" xsi:type="File" fileName="${basedir}/Log.txt" />
</target>
</targets>
<rules>
<logger name="*" minlevel="Debug" writeTo="Honeypot,normal" />
</rules>
</nlog>
我基于FilteringWrapper
来自 here 的示例.如果我的配置正确,它应该工作的方式是所有消息都将记录到“Log.txt”,并且具有非空异常的消息将记录到“Honeypot.txt”。
关于.net - 如何将 NLog 目标配置为仅记录异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9306835/