Say I have a standard JSON log as in the example in the docs (below)
{
"logger":"com.foo.Bar",
"timestamp":"1376681196470",
"level":"INFO",
"thread":"main",
"message":"Message flushed with immediate flush=true"
}
Now I want to add custom info to this log like so:
{
"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"
}
Is there a way to do this? The docs don't seem to mention anything about adding properties to the log object. Do I need to make a custom layout or programmatically add fields or what?
relevant log4j2 docs
This can be archived simply via the the config file.
See my 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
Custom fields are always last, in the order they are declared. The values support lookups
Like @alan7678 said -
A custom layout was also the solution for me.
@Plugin(name = "ExtendedJsonLayout", category = Node.CATEGORY,
elementType = Layout.ELEMENT_TYPE, printObject = true)
public class ExtendedJsonLayout extends AbstractJacksonLayout {
// Lots of code!
}
I created a Log4j2 layout plugin called "extended-jsonlayout". You can include it in your project with Maven or Gradle. Check it out here -
https://github.com/savantly-net/log4j2-extended-jsonlayout
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With