Logging json posts with resteasy

人盡茶涼 提交于 2020-01-11 08:36:09

问题


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


回答1:


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).




回答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.



来源:https://stackoverflow.com/questions/24180221/logging-json-posts-with-resteasy

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!