我正在使用Spring Boot编写Web Rest Web服务.
我想记录我的webservice处理请求所花费的时间.
另外我想记录调用的头文件,方法和URI.
几个月前我使用ContainerRequestFilter和ContainerResponseFilter filter()方法在我的球衣网络服务中做了类似的工作.
另外,AOP更好还是过滤?
最佳答案
你试过像这样的基本过滤器吗?
import java.io.IOException;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
@Component
@WebFilter("/*")
public class StatsFilter implements Filter {
private static final Logger LOGGER = LoggerFactory.getLogger(StatsFilter.class);
@Override
public void init(FilterConfig filterConfig) throws ServletException {
// empty
}
@Override
public void doFilter(ServletRequest req,ServletResponse resp,FilterChain chain) throws IOException,ServletException {
long time = System.currentTimeMillis();
try {
chain.doFilter(req,resp);
} finally {
time = System.currentTimeMillis() - time;
LOGGER.trace("{}: {} ms ",((HttpServletRequest) req).getRequestURI(),time);
}
}
@Override
public void destroy() {
// empty
}
}