• 日志记录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 相应注释掉即可。

  • 相关阅读:
    中国剩余定理
    hdu1808-Halloween treats(抽屉原理)
    快速幂算法
    因子和与因子个数
    乘性函数
    HDU 2669 Romantic (扩展欧几里得定理)
    扩展欧几里得算法
    Bi-shoe and Phi-shoe(欧拉函数)
    欧拉函数
    [51nod]1284 2 3 5 7的倍数(容斥原理)
  • 原文地址:https://www.cnblogs.com/zhaideyou/p/5914888.html
Copyright © 2020-2023  润新知