我正在使用Log4j日志记录。
由于Jersey 2.25使用java util日志记录,因此请求和响应未被记录
在旧款运动衫中,我有自定义过滤器。
是否有人有想法修复它。
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;
import java.util.Map;
import javax.ws.rs.container.ContainerRequestFilter;
import javax.ws.rs.container.ContainerResponseFilter;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.HttpHeaders;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.MultivaluedMap;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.protocol.HttpContext;
import org.glassfish.jersey.message.internal.ReaderWriter;
import org.glassfish.jersey.server.ContainerException;
import org.glassfish.jersey.server.ContainerRequest;
import org.glassfish.jersey.server.ContainerResponse;
import org.glassfish.jersey.server.ResourceConfig;
import org.glassfish.jersey.server.spi.ContainerResponseWriter;
public class LoggingFilter implements ContainerRequestFilter, ContainerResponseFilter {
/**
* If true the request and response entities (if present) will not be logged. If false the request
* and response entities will be logged.
* <p>
* The default value is false.
*/
public static final String FEATURE_LOGGING_DISABLE_ENTITY =
"com.sun.jersey.config.feature.logging.DisableEntitylogging";
private static final Log LOGGER = LogFactory.getLog(LoggingFilter.class.getName());
private static final String NOTIFICATION_PREFIX = "* ";
private static final String REQUEST_PREFIX = "> ";
private static final String RESPONSE_PREFIX = "< ";
private final Log logger;
private @Context HttpContext hc;
private @Context ResourceConfig rc;
private long id = 0;
/**
* Create a logging filter logging the request and response to a default JDK logger, named as the
* fully qualified class name of this class.
*/
public LoggingFilter() {
this(LOGGER);
}
/**
* Create a logging filter logging the request and response to a JDK logger.
*
* @param logger the logger to log requests and responses.
*/
public LoggingFilter(Log logger) {
this.logger = logger;
}
private synchronized void setId() {
if (hc.getAttribute("request-id") == null) {
hc.setAttribute("request-id", Long.toString(++id));
}
}
private StringBuilder prefixId(StringBuilder b) {
b.append(hc.getAttribute("request-id").toString()).append(" ");
return b;
}
public ContainerRequest filter(ContainerRequest request) {
setId();
final StringBuilder b = new StringBuilder();
printRequestLine(b, request);
printRequestHeaders(b, request.getRequestHeaders());
if (rc.getProperties().get(FEATURE_LOGGING_DISABLE_ENTITY)) {
logger.debug(b.toString());
return request;
} else {
ByteArrayOutputStream out = new ByteArrayOutputStream();
InputStream in = request.getEntityInputStream();
try {
if (in.available() > 0) {
ReaderWriter.writeTo(in, out);
byte[] requestEntity = out.toByteArray();
try {
String contentType = request.getRequestHeaders().getFirst(HttpHeaders.CONTENT_TYPE);
if (contentType != null && (contentType.startsWith("image")
|| contentType.equals("application/octet-stream"))) {
b.append("Binary content: " + contentType).append("\n");
} else {
printEntity(b, requestEntity);
}
} catch (Exception e) {
logger.warn("Failed to log request", e);
}
request.setEntityInputStream(new ByteArrayInputStream(requestEntity));
}
return request;
} catch (IOException ex) {
throw new ContainerException(ex);
} finally {
logger.debug(b.toString());
}
}
}
private void printRequestLine(StringBuilder b, ContainerRequest request) {
prefixId(b).append(NOTIFICATION_PREFIX).append("Server in-bound request").append('\n');
prefixId(b).append(REQUEST_PREFIX).append(request.getMethod()).append(" ")
.append(request.getRequestUri().toASCIIString()).append('\n');
}
private void printRequestHeaders(StringBuilder b, MultivaluedMap<String, String> headers) {
for (Map.Entry<String, List<String>> e : headers.entrySet()) {
String header = e.getKey();
for (String value : e.getValue()) {
prefixId(b).append(REQUEST_PREFIX).append(header).append(": ").append(value).append('\n');
}
}
prefixId(b).append(REQUEST_PREFIX).append('\n');
}
private void printEntity(StringBuilder b, byte[] entity) throws IOException {
if (entity.length == 0) {
return;
}
b.append(new String(entity)).append("\n");
}
private final class Adapter implements ContainerResponseWriter {
private final ContainerResponseWriter crw;
private final boolean disableEntity;
private long contentLength;
private ContainerResponse response;
private ByteArrayOutputStream baos;
private StringBuilder b = new StringBuilder();
Adapter(ContainerResponseWriter crw) {
this.crw = crw;
this.disableEntity = rc.getFeature(FEATURE_LOGGING_DISABLE_ENTITY);
}
public OutputStream writeStatusAndHeaders(long contentLength, ContainerResponse response)
throws IOException {
printResponseLine(b, response);
printResponseHeaders(b, response.getHttpHeaders());
if (disableEntity) {
logger.debug(b.toString());
return crw.writeStatusAndHeaders(contentLength, response);
} else {
this.contentLength = contentLength;
this.response = response;
return this.baos = new ByteArrayOutputStream();
}
}
public void finish() throws IOException {
if (!disableEntity) {
byte[] entity = baos.toByteArray();
try {
MediaType mediaType =
(MediaType) response.getHttpHeaders().getFirst(HttpHeaders.CONTENT_TYPE);
if (mediaType != null && "application".equals(mediaType.getType())
&& "pdf".equals(mediaType.getSubtype()) == false) {
printEntity(b, entity);
} else {
b.append("Binary content: ");
if (mediaType != null && mediaType.getType() != null
&& mediaType.getSubtype() != null) {
b.append(mediaType.getType());
b.append("/");
b.append(mediaType.getSubtype());
}
b.append("\n");
}
} catch (Exception e) {
logger.error("Failed to log response", e);
}
//Output to log
logger.debug(b.toString());
// Write out the headers and buffered entity
OutputStream out = crw.writeStatusAndHeaders(contentLength, response);
out.write(entity);
}
crw.finish();
}
}
public ContainerResponse filter(ContainerRequest request, ContainerResponse response) {
setId();
response.setContainerResponseWriter(new Adapter(response.getContainerResponseWriter()));
return response;
}
private void printResponseLine(StringBuilder b, ContainerResponse response) {
prefixId(b).append(NOTIFICATION_PREFIX).append("Server out-bound response").append('\n');
prefixId(b).append(RESPONSE_PREFIX).append(Integer.toString(response.getStatus())).append('\n');
}
private void printResponseHeaders(StringBuilder b, MultivaluedMap<String, Object> headers) {
for (Map.Entry<String, List<Object>> e : headers.entrySet()) {
String header = e.getKey();
for (Object value : e.getValue()) {
prefixId(b).append(RESPONSE_PREFIX).append(header).append(": ")
.append(ContainerResponse.getHeaderValue(value)).append('\n');
}
}
prefixId(b).append(RESPONSE_PREFIX).append('\n');
}
}