-
-
Save rponte/129a7339d71f55543e1013c6a5ca105b to your computer and use it in GitHub Desktop.
SlowRequestFilter, um filtro para requests lentos baseado em: https://github.com/dropwizard/dropwizard/blob/master/dropwizard-servlets/src/main/java/io/dropwizard/servlets/SlowRequestFilter.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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