【问题标题】:How to print stack trace as string once by JsonLayout of log4j2如何通过log4j2的JsonLayout将堆栈跟踪打印为字符串一次
【发布时间】:2021-04-26 09:14:30
【问题描述】:

我正在使用 log4j2 2.13.3 我的项目。 <JsonLayout compact="true" eventEol="true" stacktraceAsString="true"/>
像这样记录:

    "message": "404 NOT_FOUND \"Unable to find instance for xxx\"",
    "thrown": {
        "commonElementCount": 0,
        "localizedMessage": "404 NOT_FOUND \"Unable to find instance for xxx\"",
        "message": "404 NOT_FOUND \"Unable to find instance for xxx\"",
        "name": "org.springframework.cloud.gateway.support.NotFoundException",
        "suppressed": [
            {
                "commonElementCount": 0,
                "localizedMessage": "xxx\nStack trace:",
                "message": "xxx\nStack trace:",
                "name": "reactor.core.publisher.FluxOnAssembly$OnAssemblyException",
                "extendedStackTrace": "stack trace"
            }
        ],
        "extendedStackTrace": "stack trace"
    },

extendedStackTrace 出现两次。有没有办法让堆栈跟踪出现一次。

像这样:(复制自http://logging.apache.org/log4j/log4j-2.2/manual/layouts.html#JSONLayout

[
  {
    "logger":"com.foo.Bar",
    "timestamp":"1376681196470",
    "level":"INFO",
    "thread":"main",
    "message":"Message flushed with immediate flush=true"
  },
  {
    "logger":"com.foo.Bar",
    "timestamp":"1376681196471",
    "level":"ERROR",
    "thread":"main",
    "message":"Message flushed with immediate flush=true",
    "throwable":"stack trace"
  }
]

【问题讨论】:

    标签: log4j2


    【解决方案1】:

    如果您想以 JSON 格式记录,我建议您升级并使用新的 JsonTemplateLayout。它使您可以更好地控制生成的输出。

    为了记录到 ELK 堆栈,我更喜欢使用 GELF 布局和 SocketAppender 将日志发送到 Logstash。请参阅Logging in the Cloud 了解更多信息。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-11-12
      • 1970-01-01
      • 2013-09-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多