I had the same problem and was solved differently, so I leave my answer here, although the question is already marked as answered correctly.
I implemented a ContainerResponseFilter and introduced Providers through which I received a MessageBodyWriter for a specific response entity and a specific MediaType ; then I used it to write the object to an accessible OutputStream , which I used to register the object.
This approach allows you to capture the exact payload of the response, and not just the object attached to the Response , that is, if the object is serialized as JSON, then you will write JSON, if it is serialized as XML, you will register XML. If using the toString() method of an attached object is enough, this approach is just a useless computational cost.
Here is the code (the trick is done in the CustomResponseLogger.payloadMessage function):
@Provider public class CustomResponseLogger implements ContainerResponseFilter { private static final Logger LOGGER = LoggerFactory.getLogger(CustomResponseLogger.class); @Context private Providers providers; @Override public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext) throws IOException { String message = new String("Outgoing message").concat(System.lineSeparator()); if (responseContext.getMediaType() != null) message = message.concat("Content-Type: ").concat(responseContext.getMediaType().toString()).concat(System.lineSeparator()); message = message.concat("Payload: ").concat(payloadMessage(responseContext)).concat(System.lineSeparator()); LOGGER.info(message); } private String payloadMessage(ContainerResponseContext responseContext) throws IOException { String message = new String(); if (responseContext.hasEntity()) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); Class<?> entityClass = responseContext.getEntityClass(); Type entityType = responseContext.getEntityType(); Annotation[] entityAnnotations = responseContext.getEntityAnnotations(); MediaType mediaType = responseContext.getMediaType(); @SuppressWarnings("unchecked") MessageBodyWriter<Object> bodyWriter = (MessageBodyWriter<Object>) providers.getMessageBodyWriter(entityClass, entityType, entityAnnotations, mediaType);
Hope this helps!
source share