C# Nlog输出字符(如果异常不为空)
Nlog中是否有方法仅在异常不为null时输出特定字符。例如,我的布局是:C# Nlog输出字符(如果异常不为空),c#,asp.net,nlog,C#,Asp.net,Nlog,Nlog中是否有方法仅在异常不为null时输出特定字符。例如,我的布局是: layout="${longdate}|${callsite:skipFrames=1}|${message}|${exception:format=tostring}" 如果我调用NLog.Debug(“Hello”),输出将是: 2015-12-07 11:50:00.5114|MyDll.MyClass.MyMethod|Hello| 正在打印最后一个字符|。是否有办法防止出现这种情况,并且只有在打印出实际异
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
参数,只有出现异常时才会输出。要在消息和异常之间留出一个空格:
<variable name="StdLayout"
value="${longdate} | ${level} | ${logger} | ${message:exceptionSeparator= }${exception:format=tostring}" />
您可以为此使用
${onexception:internal}
布局渲染器
${message}${onexception:|${exception:format=Type,Message,StackTrace,Data}}
如果存在异常,它将在“|”前面加上您指定的异常格式。如果不存在异常,则仅呈现${message} 我将结合以上两个答案
- 当布局呈现类似答案时使用
,但我认为首选使用异常的消息来检测是否为null的异常,如下所示
- 使用
layout呈现类似答案onexception
我更喜欢使用第二个建议我在理解这是如何工作的时候遇到了困难,你能根据我上面的问题给我举个例子吗?让我困惑的是,你把一个目标放在一个目标里面,它怎么知道要显示哪个消息?我仍然需要显示常规消息。即使您已经找到解决方案,我也会回答您:)。语法有点混乱。这是一个单一的目标,而不是一个包含在另一个目标中。要显示常规消息和异常,您可以使用skalinkin answer,这样会更简单。因此,我可以在message子句中的
=
后面加一个空格,而不是
?这将导致只有在出现异常时才打印出
?我使用layout=“${longdate}}|${callsite:skipFrames=1}}|${message:exceptionSeparator=|}${exception:format=tostring}”尝试了这一点,但它没有打印出来。我还尝试了一个空间,它仍然没有工作。当存在异常时,它不会被打印出来。我的第一个检查是nLog版本。。。但我目前只能有限地访问包含上述配置的项目。
layout="${longdate}|${message}${when:when=length('${exception:format=tostring}')>0:Inner=|}${exception:format=tostring}"
layout="${longdate}|${message}${onexception:inner=|Exception\: ${exception:format=tostring}}"