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

项目中实现日志traceId

程序员文章站 2022-07-03 15:40:33
...
@Component
@Slf4j
public class LogInterceptor implements HandlerInterceptor {

    private static final String TRACE_ID = "traceId";

    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse
            , Object object)  {
        try {
            MDC.put(TRACE_ID, getMapping(httpServletRequest) + "-"
                    + uid(httpServletRequest) + "-"
                    + UUID.randomUUID().toString().replaceAll("-", "").substring(0, 16));
        } catch (Exception e) {
            log.warn("LogInterceptor preHandle fail, e: {}", e.toString());
        }

        return true;
    }

    private String getMapping(HttpServletRequest httpServletRequest) {
        try {
            String url = httpServletRequest.getRequestURL().toString();
            int index = url.indexOf(".com");
            if (index > 0){
                url = url.substring(index + 4);
            }else {
                index = url.indexOf("9092");
                if (index > 0){
                    url = url.substring(index + 4);
                }
            }
            return url.substring(1, url.length()).replaceAll("/", "-");
        } catch (Exception e) {
            log.warn("LogInterceptor getMapping fail, e: {}", e);
            return "";
        }
    }

    private String uid(HttpServletRequest httpServletRequest) {
        Long uid = null;
        try {
            uid = AuthInterceptor.getUid();
            if (null == uid) {
                String arg = httpServletRequest.getParameter("uid");
                if (StringUtils.isNotBlank(arg)) uid = Long.parseLong(arg);
            }
        } catch (Exception e) {
            log.warn("LogInterceptor getUid fail, e: {}", e.toString());
        }
        return uid == null ? "uid" : String.valueOf(uid);
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse,
                           Object object, ModelAndView modelAndView) {
        try {
            MDC.remove(TRACE_ID);
        } catch (Exception e) {
            log.warn("LogInterceptor postHandle MDC.remove(TRACE_ID) fail, e: {}", e.toString());
        }
    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse,
                                Object object, Exception e) throws Exception {
    }


}

相关标签: java