其他分享
首页 > 其他分享> > MDCFilter

MDCFilter

作者:互联网

package com.common.filter;

import lombok.extern.slf4j.Slf4j;
import org.slf4j.MDC;
import org.springframework.context.annotation.Configuration;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.lang.management.ManagementFactory;
import java.lang.management.RuntimeMXBean;
import java.util.UUID;

@Configuration
@Slf4j
public class MDCFilter implements Filter {
    private static final String SESSION_KEY = "sessionId";
    @Override
    public void init(FilterConfig filterConfig) {
        //

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
     
        HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
        mdc(httpServletRequest);
        filterChain.doFilter(httpServletRequest, servletResponse);
    }

    @Override
    public void destroy() {
        //
    }

    public void mdc(HttpServletRequest httpServletRequest){
        String url = httpServletRequest.getRequestURI();
        MDC.put("RequestIP",httpServletRequest.getRemoteAddr());
        MDC.put("Module",url);
        MDC.put("RemoteHost",httpServletRequest.getRemoteHost());
        MDC.put("ServerPort",httpServletRequest.getServerPort()+"");
        MDC.put("ServerIP",httpServletRequest.getLocalAddr());
        RuntimeMXBean runtime = ManagementFactory.getRuntimeMXBean();
        String name = runtime.getName();
        MDC.put("ProcessID ",name.substring(0, name.indexOf('@')));
        MDC.put("Thread", Thread.currentThread().getName());

        try{
            String sessionId = UUID.randomUUID().toString().replace("-", "");
            MDC.put(SESSION_KEY, sessionId);
        }catch (Exception e){
            log.warn("-------------set SESSION_KEY 异常---------------", e);
        }
    }
}

 

标签:httpServletRequest,MDC,void,MDCFilter,put,import,public
来源: https://www.cnblogs.com/tiancai/p/16489463.html