Skip to content

Instantly share code, notes, and snippets.

@alexandreaquiles
Last active July 26, 2016 16:44
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save alexandreaquiles/8848971 to your computer and use it in GitHub Desktop.
Save alexandreaquiles/8848971 to your computer and use it in GitHub Desktop.
import javax.servlet.*;
import javax.servlet.annotation.*;
import javax.servlet.http.*;
import java.io.IOException;
import static java.util.concurrent.TimeUnit.NANOSECONDS;
@WebFilter (value="/*",
initParams=({
@WebInitParam(name="duration", value="1")
}))
public class SlowRequestFilter implements Filter {
private final threshold;
@Override
public void init(FilterConfig config) throws ServletException {
super(config);
this.threshold = Long.parseLong(config.getInitParameter("duration"));
}
@Override
public void destroy() {}
@Override
public void doFilter(ServletRequest request,
ServletResponse response,
FilterChain chain) throws IOException, ServletException {
final HttpServletRequest httpRequest = (HttpServletRequest) request;
final long startTime = System.nanoTime();
try {
chain.doFilter(request, response);
} finally {
final long elapsedMS = NANOSECONDS.toMillis(System.nanoTime() - startTime);
if (elapsedNS >= threshold) {
System.out.printf("Slow request: %s %s (%d ms)", httpRequest.getMethod(), getFullUrl(httpRequest), elapsedMS);
}
}
}
public static String getFullUrl(HttpServletRequest request) {
final StringBuilder url = new StringBuilder(100).append(request.getRequestURI());
if (request.getQueryString() != null) {
url.append('?').append(request.getQueryString());
}
return url.toString();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment