Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I add fields to log4j2's JSON logs

Tags:

java

json

log4j2

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

like image 555
Carson Wilcox Avatar asked Dec 07 '15 20:12

Carson Wilcox


2 Answers

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 image 134
MrSpock Avatar answered Sep 21 '22 04:09

MrSpock


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

like image 36
Jeremy Avatar answered Sep 22 '22 04:09

Jeremy