Skip to content

Instantly share code, notes, and snippets.

@TheNilesh
Last active February 23, 2018 13:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save TheNilesh/9c7f3ab13ab0511c144e33e63672b08c to your computer and use it in GitHub Desktop.
Save TheNilesh/9c7f3ab13ab0511c144e33e63672b08c to your computer and use it in GitHub Desktop.
Message converter as logger
@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