2015-12-07 43 views
2

說我有一個標準的JSON日誌如在如何添加字段log4j2的JSON日誌

{ 
    "logger":"com.foo.Bar", 
    "timestamp":"1376681196470", 
    "level":"INFO", 
    "thread":"main", 
    "message":"Message flushed with immediate flush=true" 
} 

現在我想自定義的信息添加到該日誌像這樣的文檔(下)例如:

{ 
    "logger":"com.foo.Bar", 
    "timestamp":"1376681196470", 
    "level":"INFO", 
    "thread":"main", 
    "message":"Message flushed with immediate flush=true", 
    "extrainformation":"Some very important stuff I need to include", 
    "extrainformation2":"Some other very important stuff I need to include" 
} 

有沒有辦法做到這一點?文檔似乎沒有提到有關向日志對象添加屬性的任何信息。我是否需要製作自定義佈局或以編程方式添加字段或什麼?

relevant log4j2 docs

+1

我認爲創建一個自定義佈局插件是你需要做的。您可以根據需要使用佈局來格式化打印的信息。剩下的就是從LogEvent/Message中檢索數據。 – alan7678

+1

https://logging.apache.org/log4j/2.x/manual/extending.html#Layouts – alan7678

+0

我很害怕這一點。我從來沒有寫過一個插件。我猜的好時機。謝謝! –

回答

2

像@ alan7678說 -

該自定義佈局也是對我的解決方案。

@Plugin(name = "ExtendedJsonLayout", category = Node.CATEGORY, 
    elementType = Layout.ELEMENT_TYPE, printObject = true) 
public class ExtendedJsonLayout extends AbstractJacksonLayout { 

// Lots of code! 
} 

我創建了一個名爲「extended-jsonlayout」的Log4j2佈局插件。您可以使用Maven或Gradle將其包含在您的項目中。看看這裏 -

https://github.com/savantly-net/log4j2-extended-jsonlayout

1

這可以簡單地通過配置文件進行歸檔。

見我log4j2.yaml:

Configuration: 
    status: warn 
    appenders: 
    Console: 
     name: STDOUT 
     JsonLayout: 
     complete: false 
     compact: true 
     eventEol: true 
     KeyValuePair: 
      - 
      key: extrainformation 
      value: Some very important stuff I need to include 
      - 
      key: extrainformation2 
      value: Some other very important stuff I need to include 

    Loggers: 
    Root: 
     level: "warn" 
     AppenderRef: 
     ref: STDOUT 

自定義字段是總是在最後,他們在聲明的順序。值支持lookups