我已实施" ContainerRequestFilter"记录日志文件中的每个请求,其中包括Rest API,现在我的问题是,要同时处理多个请求,这样就不会发生请求丢失,系统不应该由于额外的日志记录而导致停机,所以我们需要做一些具体的事情,或者由内部过滤器处理。
我已经提到了实现类如下。
@Provider
public class CustomLoggingFilter implements ContainerRequestFilter, ContainerResponseFilter{
final static Logger log = Logger.getLogger(CustomLoggingFilter.class);
@Context
private ResourceInfo resourceInfo;
@Override
public void filter(ContainerRequestContext requestContext)
throws IOException {
MDC.put("start-time", String.valueOf(System.currentTimeMillis()));
log.info("Entering in Resource : "+requestContext.getUriInfo().getPath());
log.info("Method Name : "+ resourceInfo.getResourceMethod().getName());
log.info("Class : "+ resourceInfo.getResourceClass().getCanonicalName());
readEntityStream(requestContext);
}
private void readEntityStream(ContainerRequestContext requestContext){
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
final InputStream inputStream = requestContext.getEntityStream();
final StringBuilder builder = new StringBuilder();
int read=0;
final byte[] data = new byte[4096];
try {
while ((read = inputStream.read(data)) != -1) {
outStream.write(data, 0, read);
}
} catch (IOException e) {
e.printStackTrace();
}
byte[] requestEntity = outStream.toByteArray();
if (requestEntity.length == 0) {
builder.append("");
} else {
builder.append(new String(requestEntity));
}
requestContext.setEntityStream(new ByteArrayInputStream(requestEntity) );
if(null != builder.toString() && builder.toString().trim().length() > 0) {
log.info("Request Parameter: {}"+builder.toString());
}
}
@Override
public void filter(ContainerRequestContext requestContext,
ContainerResponseContext responseContext) throws IOException {
String stTime = MDC.get("start-time");
if(null == stTime || stTime.length() == 0) {
return;
}
long startTime = Long.parseLong(stTime);
long executionTime = System.currentTimeMillis() - startTime;
log.info("Total request execution time :"+executionTime+" milliseconds");
}
}