You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在NLog.config自定义布局中仅当存在异常时添加": "?

解决NLog自定义布局中异常分隔符的显示问题

你之前尝试的C#三元表达式语法在NLog布局配置中不生效,NLog提供了专门的条件渲染器来实现这个需求,推荐使用${when}布局渲染器控制仅当存在异常时才输出: 分隔符。

正确的配置写法

<variable name="MyLayout" value="${message}${when:when='${exception}' != '':inner=: ${exception:format=tostring}}"/>

逻辑说明

  • ${when:when='${exception}' != ''}:判断${exception}的输出是否为空字符串(无异常时${exception}会返回空值)
  • inner=: ${exception:format=tostring}:当满足条件(存在异常)时,输出: 加上完整的异常字符串内容

配置后效果:

  • 存在异常时,日志格式为 [消息内容]: [异常详情]
  • 无异常时,仅显示 [消息内容],不会出现多余的:

也可以用${if-else}实现同样效果,写法如下:

<variable name="MyLayout" value="${message}${if-else:when='${exception}' != '':then=: ${exception:format=tostring}:else=}"/>

内容的提问来源于stack exchange,提问作者Vitaliy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.09 20:35:16