log4j2

Log4j2 JsonTemplateLayout issue


I am trying to set up json logging for log4j2 described here:

https://logging.apache.org/log4j/2.x/manual/json-template-layout.html

However, the format of the output is not matching what I expect. This is what I am getting:

{"@version":1,"source_host":"localhost","message":"hello world","thread_name":"main","@timestamp":"2021-08-17T15:44:54.948-04:00","level":"INFO","logger_name":"com.logging.test.LoggingTest"}

At first I created my own template but this wasn't working so I set it to the logstash one described in the docs:

<JsonTemplateLayout eventTemplateUri="classpath:LogstashJsonEventLayoutV1.json"/>

I am not getting the line number in the output or a lot of other fields. I know it is picking up the eventTemplateURI field because if I set it to a value I know doesn't exist then I get an exception on start up.

I am using log4j-slf4j-impl, does anything special need to be done to make it work with this?

Thanks


Solution

  • You need to explicitly set locationInfoEnabled to true - this defaults to false. If this isn't available, log4j just skips the fields that depends on this info (line number, file name, function name - probably all the fields you're missing).

    Per the documentation you linked above: toggles access to the LogEvent source; file name, line number, etc. (defaults to false set by log4j.layout.jsonTemplate.locationInfoEnabled property)

    For completeness - I also set stackTraceEnabled to true.