我希望能够从请求中打印JAX-RS 2 JSON有效负载,而不管我的应用程序服务器上的实际实现如何。
我已经尝试过在SO上提出建议的解决方案,但是所有解决方案都包含实际实现中的二进制文件(例如Jersey和类似文件),并且只允许在我的应用程序中使用javaee- api v 7.0。
我尝试在我的客户端上实现ClientRequestFilter和ClientResponseFilter,但是它们不包含序列化的实体。
这是客户的示例:
WebTarget target = ClientBuilder.newClient().register(MyLoggingFilter.class).target("http://localhost:8080/loggingtest/resources/accounts"); Account acc = target.request().accept(MediaType.APPLICATION_JSON).get(account.Account.class);
这是MyLoggingFilter的实现:
@Provider public class MyLoggingFilter implements ClientRequestFilter, ClientResponseFilter { private static final Logger LOGGER = Logger.getLogger(MyLoggingFilter.class.getName()); @Override public void filter(ClientRequestContext requestContext) throws IOException { LOGGER.log(Level.SEVERE, "Request method: {0}", requestContext.getMethod()); } @Override public void filter(ClientRequestContext requestContext, ClientResponseContext responseContext) throws IOException { LOGGER.log(Level.SEVERE, "Response status: {0}", responseContext.getStatus()); } }
因此,在尝试实现此功能时需要考虑几件事
@Override public void filter(ClientRequestContext requestContext) { Object entity = requestContext.getEntity(); String serialized = serializeEntity(entity); log(serialized);
在这里,您可以自己序列化它,也许使用Jackson ObjectMapper或其他方法。您 可以 通过这种方式进行操作,但是它可以处理的类型受到限制。如果让对象按照框架已处理的方式进行序列化,则该框架将能够支持更多类型,而不仅仅是JSON。
ObjectMapper
为了让框架处理序列化并仍然能够获取序列化的数据,我们需要使用WriterInterceptor。什么我们能做的就是设置实体输出流的ByteArrayOutputStream,然后让框架连载请求对象到 我们 ByteArrayOutputStream,那么后记记录这些字节。球衣就是这样LoggingFilter处理的。
WriterInterceptor
ByteArrayOutputStream
LoggingFilter
mark()
reset()
BufferedOutputStream
下面是一个完整的简单实现。大部分都是直接从Jersey获得的LoggingFilter,尽管只是为您的用例而精简。LoggingFilter除了实体之外,Jersey还记录了许多其他信息。我遗漏的一件事是检查字符集。我只使用了硬编码的UTF-8,因为MessageUtilJersey使用的类是特定于Jersey的。如果要使过滤器对其他字符集更为通用,则可能需要考虑解决该问题。
MessageUtil
import java.io.BufferedInputStream; import java.io.ByteArrayOutputStream; import java.io.FilterOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; import java.util.logging.Logger; import javax.annotation.Priority; import javax.ws.rs.WebApplicationException; import javax.ws.rs.client.ClientRequestContext; import javax.ws.rs.client.ClientRequestFilter; import javax.ws.rs.client.ClientResponseContext; import javax.ws.rs.client.ClientResponseFilter; import javax.ws.rs.ext.WriterInterceptor; import javax.ws.rs.ext.WriterInterceptorContext; @Priority(Integer.MIN_VALUE) public class EntityLoggingFilter implements ClientRequestFilter, ClientResponseFilter, WriterInterceptor { private static final Logger logger = Logger.getLogger(EntityLoggingFilter.class.getName()); private static final String ENTITY_STREAM_PROPERTY = "EntityLoggingFilter.entityStream"; private static final Charset DEFAULT_CHARSET = StandardCharsets.UTF_8; private final int maxEntitySize = 1024 * 8; private void log(StringBuilder sb) { logger.info(sb.toString()); } private InputStream logInboundEntity(final StringBuilder b, InputStream stream, final Charset charset) throws IOException { if (!stream.markSupported()) { stream = new BufferedInputStream(stream); } stream.mark(maxEntitySize + 1); final byte[] entity = new byte[maxEntitySize + 1]; final int entitySize = stream.read(entity); b.append(new String(entity, 0, Math.min(entitySize, maxEntitySize), charset)); if (entitySize > maxEntitySize) { b.append("...more..."); } b.append('\n'); stream.reset(); return stream; } @Override public void filter(ClientRequestContext requestContext) throws IOException { if (requestContext.hasEntity()) { final OutputStream stream = new LoggingStream(requestContext.getEntityStream()); requestContext.setEntityStream(stream); requestContext.setProperty(ENTITY_STREAM_PROPERTY, stream); } } @Override public void filter(ClientRequestContext requestContext, ClientResponseContext responseContext) throws IOException { final StringBuilder sb = new StringBuilder(); if (responseContext.hasEntity()) { responseContext.setEntityStream(logInboundEntity(sb, responseContext.getEntityStream(), DEFAULT_CHARSET)); log(sb); } } @Override public void aroundWriteTo(WriterInterceptorContext context) throws IOException, WebApplicationException { final LoggingStream stream = (LoggingStream) context.getProperty(ENTITY_STREAM_PROPERTY); context.proceed(); if (stream != null) { log(stream.getStringBuilder(DEFAULT_CHARSET)); } } private class LoggingStream extends FilterOutputStream { private final StringBuilder sb = new StringBuilder(); private final ByteArrayOutputStream baos = new ByteArrayOutputStream(); LoggingStream(OutputStream out) { super(out); } StringBuilder getStringBuilder(Charset charset) { // write entity to the builder final byte[] entity = baos.toByteArray(); sb.append(new String(entity, 0, entity.length, charset)); if (entity.length > maxEntitySize) { sb.append("...more..."); } sb.append('\n'); return sb; } @Override public void write(final int i) throws IOException { if (baos.size() <= maxEntitySize) { baos.write(i); } out.write(i); } } }
也可以看看: