zoukankan      html  css  js  c++  java
  • 请求日志添加request-id

    package com.xf.config;
    
    import java.util.Date;
    
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    import org.slf4j.MDC;
    import org.springframework.web.servlet.HandlerInterceptor;
    
    import cn.hutool.core.date.DateUtil;
    import cn.hutool.core.util.IdUtil;
    import lombok.extern.slf4j.Slf4j;
    
    @Slf4j
    public class RequestInterceptor implements HandlerInterceptor {
        public static final String REQUEST_ID_KEY = "request-id";
    
        @Override
        public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
            MDC.put(REQUEST_ID_KEY, getRequestId(request));
            log.info("拦截一下哦");
            return HandlerInterceptor.super.preHandle(request, response, handler);
        }
    
        @Override
        public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
            // 把requestId添加到响应头,以便其它应用使用
            response.addHeader(REQUEST_ID_KEY, MDC.get(REQUEST_ID_KEY));
            // 请求完成,从MDC中移除requestId
            MDC.remove(REQUEST_ID_KEY);
        }
    
        public static String getRequestId(HttpServletRequest request) {
            String requestId;
            String parameterRequestId = request.getParameter(REQUEST_ID_KEY);
            String headerRequestId = request.getHeader(REQUEST_ID_KEY);
            // 根据请求参数或请求头判断是否有“request-id”,有则使用,无则创建
            if (parameterRequestId == null && headerRequestId == null) {
                requestId = DateUtil.format(new Date(), "yyyyMMddHHmmssSSS") + IdUtil.simpleUUID().substring(0, 5);
            } else {
                requestId = parameterRequestId != null ? parameterRequestId : headerRequestId;
            }
            return requestId;
        }
    }
    <property name="log.pattern"
            value="%X{request-id} %-5level %logger{200} - [%method,%line] - %msg%n" />
  • 相关阅读:
    Vue中this.$router.push(参数) 实现页面跳转
    vue elementui .eldialog 限制高度
    D Staircase Sequences 题解(思维)
    E Magical Ornament 题解(图论+状压dp)
    软件开发工具之五:“VisualStudio.NET部署应用程序”
    软件开发工具之二 :Power Designer
    软件开发工具之八 :Visio
    软件开发工具之九 :CVS
    软件开发工具之三:NUnit
    软件开发流程实例之一 :项目概述
  • 原文地址:https://www.cnblogs.com/wanjun-top/p/13566821.html
Copyright © 2011-2022 走看看