一) 在log4j的日志中需要输出应答的status_code,不用还真不知道,HttpServletResponse接口并没有getStatus()方法。
二) 自己动手,用一个Reponse的装饰器,解决这个问题。这算是一个过滤器和装饰器设计模式的典型应用吧
import java.io.IOException; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpServletResponseWrapper; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import ying.car.shiro.ShiroUtils; /** * 记录http信息的Filter * * */ public class HttpInfoLoggingFilter implements Filter{ private static final Logger LOGGER = LoggerFactory.getLogger(HttpInfoLoggingFilter.class); @Override public void init(FilterConfig filterConfig) throws ServletException { // 无配置 } @Override public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException { HttpServletRequest request = (HttpServletRequest) req; StatusExposingServletResponse response = new StatusExposingServletResponse((HttpServletResponse) res); Integer currentUserId = getCurrentUserId(); String ip = request.getRemoteAddr(); String method = request.getMethod(); String url = request.getRequestURI(); String characterEncoding = request.getCharacterEncoding(); String referer = request.getHeader("Referer"); chain.doFilter(request, response); int status = response.getStatus(); LOGGER.info("{}, {}, {}, {}, {}, {}, {}", currentUserId, ip, method, characterEncoding, referer, url, status); } @Override public void destroy() { // 无动作 } private Integer getCurrentUserId() { Integer currentUserId = 0; try { currentUserId = ShiroUtils.getPrincipalDomainId(); } catch (Exception e) {} // apache-shiro框架 return currentUserId; } //~ ============================================================================================================================ public static class StatusExposingServletResponse extends HttpServletResponseWrapper implements HttpServletResponse { private int status = 200; public StatusExposingServletResponse(HttpServletResponse response) { super(response); } @Override public void setStatus(int sc) { this.status = sc; super.setStatus(sc); } public int getStatus() { return status; } } }
web.xml
shiroFilter org.springframework.web.filter.DelegatingFilterProxy shiroFilter /* httpInfoLoggingFilter ying.car.filter.HttpInfoLoggingFilter httpInfoLoggingFilter /*