log4j2slf4jstructured-logging

Log4j2 (and SLF4j 2.0.0-alpha1) and JsonTemplateLayout--how to serialize Messages as JSON


I'm exploring Log4j 2.14.0 and SLF4j 2.0 and trying to generate structured messages.

I've got my Appender set up with a slightly modified LogstashJsonEventLayoutV1.json,

<JsonTemplateLayout eventTemplateUri="classpath:LogstashJsonEventLayoutV1-test.json" properties="true" />

where I've removed the timestamp and hostname(I'm doing this as part of a unit test) and modified the config for "message" like so:

"message": {
        "$resolver": "message",
        "fallbackKey": "formattedMessage"}

When I log something

log4jLogger.atInfo().log(new MapMessage(Map.of("hello", "world")));

It's obviously generating JSONified log messages:

{"@version":1,"message":{"hello":"world"},"thread_name":"Test worker","level":"INFO","logger_name":"java.lang.Integer"}

In production my shop generally uses Log4J via SLF4J. I'd be willing to use the 2.0.0-alpha1 release of SLF4J to achieve this goal. How would I achieve the same thing via SLF4J's fluent API via addKeyValue?

logger.atDebug().addKeyValue("oldT", oldT).addKeyValue("newT", newT).log("Temperature changed.");

Solution

  • At the end of the day I just wrapped log4j--for this use case, there was no manna to be had for wrapping Slf4j when I could just target log4j.