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

Nlog output characters if exception not null

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|

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

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

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

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

另请参阅 "When" 布局渲染器

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

由 OP 编辑​​以显示未来访问者的工作解决方案:

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

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

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

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

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

如果有异常,会在前面加上'|'然后是您指定的任何异常格式。如果不存在异常,则只会呈现 ${message}。

我将结合以上两个答案

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

有关建议布局的更多详细信息,请参见官方文档

我更喜欢使用第二个建议