Java: How to log raw JSON as JSON and avoid escaping during logging with logback / slf4j

后端 未结 7 2217
攒了一身酷
攒了一身酷 2021-02-05 13:09

I\'m using SLF4J with Logback in a JAX-RS application... I want to log to JSON in such a way that my message is not encoded again but printed raw into the logfile:

At t

7条回答
  •  我在风中等你
    2021-02-05 13:38

    I can't see the original code that's causing your problem, but I suspect it might look like this

    JsonNode logOutput;
    String messageJSONAsString;
    

    ...

    logOutput.put("@message", messageJSONAsString);
    logger.info(objectMapper.writeValueAsString(logOutput);
    

    This will produce escaped JSON in your output because when you put the message into the output JsonNode, Jackson will re-escape it for you to make sure the output is valid JSON.

    The solution here is to put the message in your output as an ObjectNode rather than as a string. Usually you already have access to the object as an Object, in which case you can do

    ObjectNode jsonObject = objectMapper.valueToTree(messageObject);
    logOutput.put("@message", jsonObject)
    

    Otherwise, if your message is a JSON string, then parse it and add it to the output

    logoutput.put("@message", objectMapper.readTree(messageJSONAsString));
    

提交回复
热议问题