如何将字段添加到log4j2的JSON日志

Car*_*cox 6 java json log4j2

说我有一个标准的JSON日志,如docs中的示例所示(如下)

{
    "logger":"com.foo.Bar",
    "timestamp":"1376681196470",
    "level":"INFO",
    "thread":"main",
    "message":"Message flushed with immediate flush=true"
}
Run Code Online (Sandbox Code Playgroud)

现在,我想向此日志添加自定义信息,如下所示:

{
    "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"
}
Run Code Online (Sandbox Code Playgroud)

有没有办法做到这一点?文档似乎没有提及有关向日志对象添加属性的任何内容。我是否需要进行自定义布局或以编程方式添加字段或其他内容?

相关的log4j2文档

小智 5

这可以通过配置文件简单地存档。

查看我的 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
Run Code Online (Sandbox Code Playgroud)

自定义字段始终按照声明的顺序排在最后。值支持查找

  • @MrSpock如何从程序中的日志语句将值传递到此自定义字段? (2认同)

Jer*_*emy 4

就像@alan7678 说的 -

自定义布局也是我的解决方案。

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

// Lots of code!
}
Run Code Online (Sandbox Code Playgroud)

我创建了一个名为“extended-jsonlayout”的 Log4j2 布局插件。您可以使用 Maven 或 Gradle 将其包含在您的项目中。在这里查看 -

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