Generic way to log the response times of your REST resources

With RESTeasy it’s not that easy to log the response times of your resources in a generic way. The framework provides you several interceptors that you can use. And implementing two of them you can easily log your response times quite nice:

import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.Context;
import javax.ws.rs.ext.Provider;

import org.jboss.resteasy.annotations.interception.ServerInterceptor;
import org.jboss.resteasy.core.ResourceMethod;
import org.jboss.resteasy.core.ServerResponse;
import org.jboss.resteasy.spi.Failure;
import org.jboss.resteasy.spi.HttpRequest;
import org.jboss.resteasy.spi.interception.PostProcessInterceptor;
import org.jboss.resteasy.spi.interception.PreProcessInterceptor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@Provider
@ServerInterceptor
public class ResponseTimeLogger implements PreProcessInterceptor, PostProcessInterceptor {

    private static final Logger logger = LoggerFactory.getLogger(ResponseTimeLogger.class);

    public static final String REQUEST_START_TIME = "RequestStartTime";

    @Context
    private HttpServletRequest servletRequest;

    public ServerResponse preProcess(HttpRequest request, ResourceMethod resourceMethod) throws Failure, WebApplicationException {
        servletRequest.setAttribute(REQUEST_START_TIME, System.currentTimeMillis());
        return null;
    }

    @Override
    public void postProcess(ServerResponse serverResponse) {
        try {
            logger.info("Invoked resource {}.{}. ip={}, uri={}, status={}, duration={}ms,",
                    serverResponse.getResourceClass().getName(),
                    serverResponse.getResourceMethod().getName(),
                    servletRequest.getRemoteAddr(),
                    servletRequest.getRequestURI(),
                    serverResponse.getStatus(),
                    (System.currentTimeMillis() - ((Long) servletRequest.getAttribute(REQUEST_START_TIME)))
            );
        } catch (RuntimeException e) {
            logger.warn("Error while logging request data.", e);
        }
    }
}

 

Leave a Reply

Your email address will not be published. Required fields are marked *