spring-bootlogging

How to log structured with Spring Boot's new built-in structured logging support


I noticed the builtin support for structured logging that came with Spring Boot release 3.4 and decided to try and replace our current structured logging implementation that uses the logstash-logback-encoder.

While testing it out with the following log (through a slf4j logger)

log.atError().addKeyValue("entry", Map.entry("key", "value")).log("message");

I noticed the following difference in the logged output (I removed other fields that entry), first line is logstash-logback-encoder second is spring:

{"entry":{"key":"value"}}
{"entry":"key=value"}

So the logstash-logback-encoder converts my Java object to JSON while Spring Boot implementation calls toString().

Is there a simple way to log Java objects structured with the Spring implementation?


Solution

  • So after poking around in the debugger I figured out that if you add a value of type java.util.Map then it will be logged structurally (this happens in org.springframework.boot.json.JsonValueWriter in the write method). So if you want to log a pojo structurally, you could do something like this (if you have a jackson object mapper):

    log.atError().addKeyValue("entry", objectMapper.convertValue(pojo, HashMap.class)).log("message");