假设我有一个标准的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"
}
有办法做到这一点吗?文档似乎没有提到有关向日志对象添加属性的任何内容。我是否需要制作自定义布局或以编程方式添加字段或什么?
答案 0 :(得分:3)
喜欢@ 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将其包含在项目中。看看这里 -
答案 1 :(得分:3)
这可以通过配置文件存档。
请参阅我的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