问题描述
我正在寻找一种在RESTEASY框架中记录JSON帖子的方法.
I'm looking for a way to log JSON posts in a RESTEASY framework.
我想记录POST正文以记录文件,以查看客户端向我发送的内容.
I woul like to log the POST body to log file to see what the client is sending to me.
有没有可以使用的拦截器或类似的东西,我找到了PreProcessInterceptor的示例,但它似乎已弃用.
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.
我正在使用resteasy 3.0.8
I'm using resteasy 3.0.8
推荐答案
您可以使用 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));
}
}
代替检查方法和内容类型,您还可以按 @ NameBinding 仅在需要的地方.
Instead of checking for Method and Content-Type you can also register this filter per @NameBinding only where you need it.
注意::这个简单的示例复制了请求的InputStream,因此它将被读取两次(可能是性能问题).
Note: This simple example copies the InputStream of the request so it will be read twice (maybe a performance problem).
这篇关于使用resteasy记录JSON帖子的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!