首页 > 代码库 > 日志记录Filter
日志记录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, A1log4j.appender.A1=org.apache.log4j.ConsoleAppenderlog4j.appender.A1.layout=org.apache.log4j.PatternLayoutlog4j.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 相应注释掉即可。
日志记录Filter
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。