【问题标题】:Nlog output characters if exception not null如果异常不为空,则 Nlog 输出字符
【发布时间】:2015-12-07 17:01:10
【问题描述】:

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|

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

【问题讨论】:

    标签: c# asp.net nlog


    【解决方案1】:

    还请查看“何时”布局渲染器

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

    由 OP 编辑​​,为未来的访客展示可行的解决方案:

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

    【讨论】:

      【解决方案2】:

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

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

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

      【讨论】:

        【解决方案3】:

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

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

        【讨论】:

        • 所以我可以在消息子句中的= 之后放置| 而不是空格?这样会导致|只有在出现异常的情况下才会被打印出来?
        • 我用layout="${longdate}|${callsite:skipFrames=1}|${message:exceptionSeparator=|}${exception:format=tostring}" 试过了,但没有打印出来。我也用空格试过了,还是不行。当异常存在时,它不会被打印出来。
        • 我的第一个检查是在 nLog 版本上......但我目前只能有限地访问包含上述配置的项目。
        【解决方案4】:

        我会结合以上两个答案

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

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

        我更喜欢使用第二个建议

        【讨论】:

          【解决方案5】:

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

          <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”)。

          【讨论】:

          • 我无法理解它是如何工作的,你能根据我上面的问题给我一个例子吗?令我困惑的是,您将目标放在目标中,它如何知道要显示哪个消息?我仍然需要显示常规消息。
          • 即使您已经找到了解决方案,我也会回答您:)。语法有点混乱。这是一个单一的目标,而不是一个包含在另一个目标中。要显示常规消息和异常,您可以使用 skalinkin answer,它会更简单。
          猜你喜欢
          • 1970-01-01
          • 2019-12-09
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2013-11-14
          • 2021-12-22
          • 1970-01-01
          • 2015-04-30
          相关资源
          最近更新 更多