Carson Wilcox
Carson Wilcox

Reputation: 361

How do I add fields to log4j2's JSON logs

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

Upvotes: 14

Views: 12604

Answers (2)

MrSpock
MrSpock

Reputation: 1717

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

Upvotes: 6

Jeremy
Jeremy

Reputation: 3548

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

Upvotes: 4

Related Questions