Last active
February 23, 2018 13:55
-
-
Save TheNilesh/9c7f3ab13ab0511c144e33e63672b08c to your computer and use it in GitHub Desktop.
Message converter as logger
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@Component | |
public class MyMappingJackson2MessageConverter extends AbstractHttpMessageConverter<Object> { | |
private static final Logger LOGGER = LoggerFactory.getLogger("RequestResponseLogger"); | |
@Autowired | |
private ObjectMapper objectMapper; | |
@Autowired | |
private HttpServletRequest request; | |
public MyMappingJackson2MessageConverter() { | |
super(MediaType.APPLICATION_JSON_UTF8); | |
} | |
@Override | |
protected boolean supports(Class<?> clazz) { | |
return true; | |
} | |
@Override | |
protected Object readInternal(Class<? extends Object> clazz, HttpInputMessage inputMessage) | |
throws IOException, HttpMessageNotReadableException { | |
InputStream inputStream = inputMessage.getBody(); | |
String requestBody = IOUtils.toString(inputStream, StandardCharsets.UTF_8); | |
String method = request.getMethod(); | |
String uri = request.getRequestURI(); | |
LOGGER.debug("{} {}", method, uri); | |
LOGGER.debug("{}", requestBody); | |
return objectMapper.readValue(requestBody, clazz); | |
} | |
@Override | |
protected void writeInternal(Object o, HttpOutputMessage outputMessage) | |
throws IOException, HttpMessageNotWritableException { | |
String responseBody = objectMapper.writeValueAsString(o); | |
LOGGER.debug("{}", responseBody); | |
outputMessage.getBody().write(responseBody.getBytes(StandardCharsets.UTF_8)); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment