6

I'm looking for a way to log JSON posts in a RESTEASY framework.

I woul like to log the POST body to log file to see what the client is sending to me.

Is there any interceptor or something similar that I can use, I have found an example for PreProcessInterceptor but it looks like it is deprecated.

I'm using resteasy 3.0.8

simonC
  • 4,101
  • 10
  • 50
  • 78

2 Answers2

7

You can use a ContainerRequestFilter:

@Provider
public class LogFilter implements ContainerRequestFilter {

    private Logger LOG = LoggerFactory.getLogger(LogFilter.class);

    @Override
    public void filter(ContainerRequestContext requestContext) throws IOException {

        if (!"POST".equals(requestContext.getMethod()) 
                || !MediaType.APPLICATION_JSON_TYPE.equals(requestContext.getMediaType())
                || requestContext.getEntityStream() == null) {
            return;
        }

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        IOUtils.copy(requestContext.getEntityStream(), baos);
        byte[] bytes = baos.toByteArray();
        LOG.info("Posted: " + new String(bytes, "UTF-8"));
        requestContext.setEntityStream(new ByteArrayInputStream(bytes));

    }

}

Instead of checking for Method and Content-Type you can also register this filter per @NameBinding only where you need it.

Note: This simple example copies the InputStream of the request so it will be read twice (maybe a performance problem).

lefloh
  • 10,653
  • 3
  • 28
  • 50
2

As supplement of excellent answer of lefloh, I suggest replace:

!MediaType.APPLICATION_JSON_TYPE.equals(requestContext.getMediaType())

with

!MediaType.APPLICATION_JSON_TYPE.isCompatible(requestContext.getMediaType())

equals method takes into account parameters of media type, eg. charset=UTF-8, and does not work in some scenarios according to intention of lefloh. isCompatible compares only type and subtype of media type and is more suitable in this case.

PS. I know, this post should be placed as comment, but I have no enough level of reputation to do it. I also edited lefloh answer but some php and ios guys rejected it.

JuliuszJ
  • 119
  • 1
  • 7