Implementation of ContainerRequestFilter in Rest API application in java

Viewed 193

I have implemented "ContainerRequestFilter" to log each and every request in log file, which commes to Rest API, now my question is that, to handle multiple request simultaneously such that no request lost happen and system should not get down due to extra overhead of logging, so do we need to do something specific or it will be handled by filter internally.

I have mentioned implementation class as following.

@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");
    }
}
0 Answers
Related