如果异常不为null,则Nlog输出字符



在Nlog中是否有一种方法可以仅在Exception不为null的情况下输出特定字符。例如,我的布局是:

layout="${longdate}|${callsite:skipFrames=1}|${message}|${exception:format=tostring}" 

如果我调用NLog.Debug("Hello"),输出将是:

2015-12-07 11:50:00.5114|MyDll.MyClass.MyMethod|Hello|

最后一个字符|正在打印出来。有没有办法防止这种情况,只有在打印出实际的异常时才打印出来?

同时查看"何时"布局渲染器

${when:when=Condition:inner=Layout} 

由OP编辑,展示未来访客的工作解决方案:

layout="${longdate}|${callsite:skipFrames=1}|${message}${when:when=length('${exception}')>0:Inner=|}${exception:format=tostring}"

您可以为此使用${onexception:INNER}布局渲染器。

${message}${onexception:|${exception:format=Type,Message,StackTrace,Data}}

如果出现异常,它将在"|"前面加上您指定的异常格式。如果不存在异常,则只呈现${消息}。

我一直在使用$(message)exceptionSeparator参数,只有在出现异常时才会输出。给消息之间的空格一个例外:

<variable name="StdLayout" 
value="${longdate} | ${level} | ${logger} | ${message:exceptionSeparator= }${exception:format=tostring}" />

我将组合以上两个答案

  • 使用when布局呈现类似@skalinkin的答案,但我认为如果为null或否,首选使用异常的消息来检测异常,就像这样
layout="${longdate}|${message}${when:when=length('${exception:format=tostring}')>0:Inner=|}${exception:format=tostring}"
  • 使用onexception布局渲染,如@Alex answer
layout="${longdate}|${message}${onexception:inner=|Exception: ${exception:format=tostring}}"

有关建议布局的更多详细信息,请点击此处官方文档

  • https://github.com/NLog/NLog/wiki/When-Layout-Renderer
  • https://github.com/NLog/NLog/wiki/OnException-Layout-Renderer

I首选使用第二个建议

您可以定义一个明确测试异常是否为空的目标:

<target name="fileAsException"
        xsi:type="FilteringWrapper"
        condition="length('${exception}')>0">
  <target xsi:type="File"
          fileName="c:my pathexceptions.log"
          layout="${ExceptionVerboseLayout}" />
</target>

(请参阅"condition="length('${exception}')>0">"行)
您可以将其与特定布局绑定(在我的示例中为"ExceptionVerboseLayout")。

最新更新