欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

ELK+MDC追踪日志 ---- Spring的Filter实现

程序员文章站 2022-03-05 08:11:05
...

Maven依赖

<dependency>
   <groupId>org.slf4j</groupId>
   <artifactId>slf4j-log4j12</artifactId>
   <version>1.7.25</version>
</dependency>

log4j.properties

只用看%X{uuid}那里

log4j.logger.com.ibatis=debug
log4j.logger.com.ibatis.common.jdbc.SimpleDataSource=debug
log4j.logger.com.ibatis.common.jdbc.ScriptRunner=debug
log4j.logger.com.ibatis.sqlmap.engine.impl.SqlMapClientDelegate=debug
log4j.logger.java.sql.Connection=debug
log4j.logger.java.sql.Statement=debug
log4j.logger.java.sql.PreparedStatement=debug

log4j.rootLogger = INFO,fileout,console
log4j.logger.crmLogger=DEBUG,fileout,console

log4j.appender.fileout=org.apache.log4j.DailyRollingFileAppender
log4j.appender.fileout.Threshold=DEBUG 
log4j.appender.fileout.File=${log4jUrl}

log4j.appender.fileout.Append=true
log4j.appender.fileout.DatePattern='.'yyyyMMdd
log4j.appender.fileout.layout=org.apache.log4j.PatternLayout 
log4j.appender.fileout.layout.ConversionPattern=[%d{yyyy-MM-dd HH:mm:ss.SSS}] [%5p] [uuid=%X{uuid}] [%t] [%class.%M] %m%n

log4j.appender.console=org.apache.log4j.ConsoleAppender
log4j.appender.console.layout=org.apache.log4j.PatternLayout
log4j.appender.console.layout.ConversionPattern=[%d{yyyy-MM-dd HH:mm:ss.SSS}] [%5p] [uuid=%X{uuid}] [%t] [%class.%M] %m%n
log4j.appender.console.Threshold=DEBUG 
log4j.appender.file.encoding=UTF-8


log4j.logger.org.springframework=error,fileout
log4j.logger.org.apache.commons=error,fileout
log4j.logger.net.sf.ehcache=error,fileout
log4j.logger.org.apache.ibatis=error,fileout
log4j.logger.org.mybatis.spring=error,fileout
log4j.logger.com.fuiou= debug,fileout

实现Filter

  • 1、实现一个Filter,使用MDC.put(key, val)写入需要打印的参数。
import org.slf4j.MDC;

public class MDCFilter implements Filter {

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws IOException,ServletException {        
        try {
            MDC.put("requestMethod", request.getMethod().toUpperCase());
            MDC.put("requestUri", request.getRequestURI());
            MDC.put("uuid", UUID.randomUUID().toString().replace("-", ""));
            MDC.put("ip", request.getRemoteAddr());
            User requestUser = (User) request.getAttribute(Constants.REQUEST_USER);
            if (requestUser != null) {
                MDC.put("uid", String.valueOf(requestUser.getId()));
            }
        } catch (Exception e) {
            logger.error("init MDC error.", e);
        }
        try {
            filterChain.doFilter(request, response);
        } finally {
            MDC.clear();
        }
    }
}
  • 2、也可以在项目中现有的Filter中doFillter中加上一行,但记得要在最后finallyMDC.clear();
    如果web.xml有多个拦截器,可以选择在最后一个Filter的finally调用MDC.clear();
 public void doFilter(ServletRequest req, ServletResponse res,
            FilterChain chain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) res;
        try {
         	MDC.put("uuid", UUID.randomUUID().toString().replaceAll("-", ""));
         	// ......此处省略其他处理步骤
            // 继续过滤
        	chain.doFilter(req, res);
        } finally {
            MDC.clear();
        }         	
 }