'How to write valid JSON data in logs in java Spring Boot
Logs file currently
"message":"{\"productID\":\"999\",\"productName\":\"Shoes",\"productCost\":\"1200\"}"
the data is fine but JSON format it not valid
Code currently used to convert a model into JSON
public static String test(Object obj) {
ObjectMapper ow = new ObjectMapper();
try {
ow.setSerializationInclusion(JsonInclude.Include.NON_NULL);
return ow.writer().writeValueAsString(obj);
} catch (JsonProcessingException e) {
e.printStackTrace();
}
return "";
}
Log code used to write in log file.
logg.info(MainClass.test(productBean);
Log configurations in logback.xml. logger I have used is of org.slf4j
``
<appender name="testLog">
<filter class="ch.qos.logback.classic.filter.ThresholdFilter">
<level>info</level>
</filter>
<file>C:/Logs/logs.log</file>
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<fileNamePattern>C:/Logs/logs.log</fileNamePattern>
<maxHistory>30</maxHistory>
</rollingPolicy>
</appender>
<logger name = "com.demo" level="INFO">
<appender-ref ref="testLog" />
</logger>
``
Solution 1:[1]
In the logback.xml where we specify our appenders and loggers we need to add the encoder tag for our appender.
<encoder>
<pattern>%date{yyyy-MM-dd HH:mm:ss:SSS} | %-5level [%thread] %message%n</pattern>
</encoder>
Solution 2:[2]
String formattedMessage = message.replaceAll("\\\\", "");
Because the backslash is the escaping character in a regular expression replaceAll() receives one as parameter, which has to be escaped too.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | BigArmsWriteSmallCode |
Solution 2 | Shubam Virdi |