簡體   English   中英

如何使用 log4j2.xml 自定義 json 格式的日志異常

[英]How to customize logs exception in json format using log4j2.xml

我嘗試編寫自己的模式布局,它以 json 格式寫入日志,但 50% 的異常在 json 中,50% 不在 json 中。 這個邏輯應該適用於所有異常,但我無法理解為什么這在少數情況下不起作用。

下面是我的 log4j2.xml 的模式布局:

    <!-- Rolling File Appender -->
    <Console name="Console">
        <target>SYSTEM_OUT</target>
        <PatternLayout
            pattern="{&quot;timestamp&quot;:&quot;%d&quot;, &quot;docker_id&quot;:&quot;%X{DockerID}&quot;, &quot;app_name&quot;:&quot;${component_name}&quot;,&quot;app_version&quot;:&quot;${component_version}&quot;, &quot;request_id&quot;:&quot;%X{RequestID}&quot;, &quot;tenant&quot;:&quot;%X{Tenant}&quot;,&quot;log_level&quot;:&quot;%p&quot;, &quot;file&quot;:&quot;%C.%M&quot;,&quot;line&quot;:&quot;%L&quot;, &quot;message&quot;:&quot;%replace{%replace{%msg}{&quot;}{}}{[\r\n]+}{ }&quot;,&quot;exception&quot;:&quot;%enc{%rEx{full}}{JSON}&quot;%rEx{0}}%n" />
     </Console>
你能幫我解決這個問題嗎? 謝謝!

我當然會避免這種做法,因為已經有一個更好的替代方案: Log4j 2 提供的 JsonTemplateLayout。

以下模板應該為您完成這項工作:

{
  "timestamp": {
    "$resolver": "timestamp",
    "epoch": {
      "unit": "millis",
      "rounded": true
    }
  },
  "docker_id": {
    "$resolver": "mdc",
    "key": "DockerID"
  },
  "app_name": "${component_name}",
  "app_version": "${component_version}",
  "request_id": {
    "$resolver": "mdc",
    "key": "RequestID"
  },
  "tenant": {
    "$resolver": "mdc",
    "key": "Tenant"
  },
  "log_level": {
    "$resolver": "level",
    "field": "name"
  },
  "file": {
    "$resolver": "pattern",
    "pattern": "%C.%M",
    "stackTraceEnabled": false
  },
  "line": {
    "$resolver": "source",
    "field": "lineNumber"
  },
  "message": {
    "$resolver": "message",
    "stringified": true
  },
  "exception": {
    "$resolver": "exception",
    "field": "stackTrace",
    "stackTrace": {
      "stringified": true
    }
  }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM