日志记录Filter

Filter也可以日志记录,在request 之前后, 该filter 使用Apache 日只记录工具,记录客户IP ,访问URI 以及消耗时间。

LogFilter.java

package com.helloweenvsfei.filter;

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 org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory; public class LogFilter implements Filter { private Log log = LogFactory.getLog(this.getClass()); private String filterName; public void init(FilterConfig config) throws ServletException { // 获取 Filter 的 name,配置在 web.xml 中
filterName = config.getFilterName(); log.info("启动 Filter: " + filterName); } public void doFilter(ServletRequest req, ServletResponse res,
FilterChain chain) throws IOException, ServletException { HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse) res; long startTime = System.currentTimeMillis();
String requestURI = request.getRequestURI(); requestURI = request.getQueryString() == null ? requestURI
: (requestURI + "?" + request.getQueryString()); chain.doFilter(request, response); long endTime = System.currentTimeMillis(); log.info(request.getRemoteAddr() + " 访问了 " + requestURI + ", 总用时 "
+ (endTime - startTime) + " 毫秒。"); } public void destroy() {
log.info("关闭 Filter: " + filterName);
} }

log4j.properties   使用jar log4j.jar 和 commons-logging.jar

可参考

commmons_logging 和 log4j 之日志笔记一

log4j.rootLogger=INFO, A1

log4j.appender.A1=org.apache.log4j.ConsoleAppender
log4j.appender.A1.layout=org.apache.log4j.PatternLayout
log4j.appender.A1.layout.ConversionPattern=%-d{yyyy-MM-dd HH\:mm\:ss,SSS} [%l]-[%p] %m%n

web.xml

<filter>
<filter-name>logFilter</filter-name>
<filter-class>com.helloweenvsfei.filter.LogFilter</filter-class>
</filter> <filter-mapping>
<filter-name>logFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>

如不需要日志Filter ,可把web.xml 相应注释掉即可。

上一篇:HihoCoder1182 欧拉路(Fleury算法)


下一篇:MySQL查询不区分大小写的sql写法