使用log4j MDC打印日志信息


使用log4j的MDC功能,打印更加详细的日志信息,方便ELK等日志收集整理工具分析


1、创建Filter类

package com.chz.apps.core.filters;

import com.alibaba.fastjson.JSON;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.MDC;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.UUID;

public class LoggerMDCFilter extends OncePerRequestFilter implements Filter {

    private static final String regex=".*(css|ico|jpg|jpeg|png|gif|js)";

    private static org.apache.log4j.Logger log         = org.apache.log4j.LogManager.getLogger(LoggerMDCFilter.class);

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException {
        String requestedUri=request.getRequestURL().toString();
        if(requestedUri.matches(regex)){
            chain.doFilter(request, response);
            return;
        }

        try {
            MDC.put("req.remoteAddr", StringUtils.defaultString(request.getRemoteAddr()));
            //为每一个请求创建一个ID,方便查找日志时可以根据ID查找出一个http请求所有相关日志
            MDC.put("req.id", StringUtils.remove(UUID.randomUUID().toString(),"-"));

            //处理http请求日志信息
            Map<String,Object> params = new LinkedHashMap<String,Object>();
            params.put("uri",request.getRequestURI());
            params.put("URIWithQueryString", request.getRequestURI() + (request.getQueryString() == null ? "" : "?"+request.getQueryString()));
            params.put("method",request.getMethod());
            params.put("queryString",request.getQueryString());
            params.put("params", JSON.toJSONString(request.getParameterMap()));
            log.info(params);

            chain.doFilter(request, response);
        }finally {
            clearMDC();
        }
    }

    private void clearMDC() {
        Map map = MDC.getContext();
        if(map != null) {
            map.clear();
        }
    }
}


2、添加到web.xml配置文件中

<filter>
   <filter-name>mdcFilter</filter-name>
   <filter-class>com.chz.apps.core.filters.LoggerMDCFilter</filter-class>
</filter>

<filter-mapping>
   <filter-name>mdcFilter</filter-name>
   <url-pattern>/*</url-pattern>
</filter-mapping>


3、添加log4j配置文件

修改前:
[%d{HH:mm:ss SSS\} %-5p] %m%n

修改后:
[%X{req.remoteAddr}-%X{req.id}] [%d{HH:mm:ss SSS\} %-5p] %m%n


上一篇 下一篇

分享

热门文章