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

如何让Log4j JSONLayout的stacktraceAsString排除thrown对象中的cause

解决Log4j JSONLayout异常日志中cause对象重复输出的问题

你当前使用的JSONLayout配置已能输出工具可识别的结构化异常日志,但由于stacktraceAsString="true"会将包含“Caused by:”的完整栈跟踪写入extendedStackTrace,同时thrown对象下仍保留cause子对象,导致内容重复。以下是两种直接排除cause对象的方案:

方案1:使用excludeFields精准排除(Log4j 2.17.0+)

在JSONLayout中添加excludeFields属性,指定要排除的嵌套字段路径thrown.cause:

<Console name="Console" follow="true">
  <JSONLayout eventEol="true" compact="true" properties="true" stacktraceAsString="true"
              excludeFields="thrown.cause"/>
</Console>

该属性是Log4j 2.17.0及以上版本新增的特性,可直接过滤指定的嵌套字段,彻底避免重复内容。

方案2:用FieldFilter过滤(兼容低版本)

如果你的Log4j版本低于2.17.0,可通过自定义FieldFilter拒绝输出thrown.cause字段:

<Console name="Console" follow="true">
  <JSONLayout eventEol="true" compact="true" properties="true" stacktraceAsString="true">
    <FieldFilter key="thrown.cause" onMatch="DENY" onMismatch="NEUTRAL"/>
  </JSONLayout>
</Console>

FieldFilter会匹配指定字段路径,匹配成功时拒绝输出该字段,同时保留extendedStackTrace中的完整栈跟踪信息。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.12 14:49:58