Java: How to log raw JSON as JSON and avoid escaping during logging with logback / slf4j
If you have a Json formatted messages, the upper solutions work, but are not so nice, since you donĀ“t want to call a logstash specific code, each time you use your logger in the code.
Just adding a
net.logstash.logback.encoder.LogstashEncoder
is not enough, since the message itsself stays escaped. To solve this, try the following in your logback.xml:
<encoder class="net.logstash.logback.encoder.LoggingEventCompositeJsonEncoder"> <providers> <timestamp/> <version/> <loggerName/> <pattern> <pattern> { "jsonMessage": "#asJson{%message}" } </pattern> </pattern> </providers></encoder>
The #asJson pattern will unescape your message.
I ran into the same problem. I solved it with
<encoder class="net.logstash.logback.encoder.LogstashEncoder"> </encoder
instead of
<encoder class="net.logstash.logback.encoder.LoggingEventCompositeJsonEncoder">
In my java code I used:
SRV_PERF_LOGGER.info(net.logstash.logback.marker.Markers.appendRaw("message", jackson.writeValueAsString(dto)), null);