zoukankan      html  css  js  c++  java
  • spring boot web请求信息和返回数据日志输出

    1.spring boot web http 请求日志信息输出

    @Aspect
    @Component
    public class WebLogAspect {
        private final static Logger logger = LoggerFactory.getLogger(WebLogAspect.class);
        /** 以 controller 包下定义的所有请求为切入点 */
        @Pointcut("execution(public * com.dkn..controller.*.*(..))")
        public void webLog() {}
        /**
         * 在切点之前织入
         * @param joinPoint
         * @throws Throwable
         */
        @Before("webLog()")
        public void doBefore(JoinPoint joinPoint) throws Throwable {
            // 开始打印请求日志
            ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            HttpServletRequest request = attributes.getRequest();
            // 打印请求相关参数
            logger.info("========================================== Start ==========================================");
            // 打印请求 url
            logger.info("URL            : {}", request.getRequestURL().toString());
            // 打印 Http method
            logger.info("HTTP Method    : {}", request.getMethod());
            // 打印调用 controller 的全路径以及执行方法
            logger.info("Class Method   : {}.{}", joinPoint.getSignature().getDeclaringTypeName(), joinPoint.getSignature().getName());
            // 打印请求的 IP
            logger.info("IP             : {}", getIpAddr(request));
            // 打印请求入参
            printRequestParamsLog(joinPoint);
            // 打印header信息
            printHeaderInfoLog(request);
        }
        /**
         * 在切点之后织入
         * @throws Throwable
         */
        @After("webLog()")
        public void doAfter() throws Throwable {
            logger.info("=========================================== End ===========================================");
            // 每个请求之间空一行
            logger.info("");
        }
    
        /**
         * 环绕
         * @param proceedingJoinPoint
         * @return
         * @throws Throwable
         */
        @Around("webLog()")
        public Object doAround(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
            long startTime = System.currentTimeMillis();
            Object result = proceedingJoinPoint.proceed();
            // 打印出参
            //logger.info("Response Result: {}", new Gson().toJson(result));
            logger.info("Response Result: {}", JSON.toJSONString(result));
            // 执行耗时
            logger.info("Use Time       : {} ms", System.currentTimeMillis() - startTime);
            return result;
        }
    
    
        /**
         * 打印request请求参数
         */
        public void printRequestParamsLog(JoinPoint joinPoint){
            String[] parameterNames = ((MethodSignature) joinPoint.getSignature()).getParameterNames();
            Object[] parameterValues = joinPoint.getArgs(); // 获取方法参数
            StringBuffer paramsBuf = new StringBuffer();
            for (int i = 0; i < parameterValues.length; i++) {
                logger.info("Request params : {}", parameterNames[i]+" = "+parameterValues[i]);
            }
        }
    
        /**
         * 打印header信息
         */
        public void printHeaderInfoLog(HttpServletRequest request){
            Enumeration<String> headerNames = request.getHeaderNames();
            while (headerNames.hasMoreElements()) {
                String key = (String) headerNames.nextElement();
                String value = request.getHeader(key);
                logger.info("Header         : {}", key+" = "+value);
            }
        }
    
        /**
         * @Description: 获取ip
         */
        public String getIpAddr(HttpServletRequest request) {
            String ipAddress = null;
            ipAddress = request.getHeader("x-forwarded-for");
            if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
                ipAddress = request.getHeader("Proxy-Client-IP");
            }
            if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
                ipAddress = request.getHeader("WL-Proxy-Client-IP");
            }
            if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
                ipAddress = request.getRemoteAddr();
            }
            // 对于通过多个代理的情况,第一个IP为客户端真实IP,多个IP按照','分割
            if (ipAddress != null && ipAddress.length() > 15) { // "***.***.***.***".length()
                // = 15
                if (ipAddress.indexOf(",") > 0) {
                    ipAddress = ipAddress.substring(0, ipAddress.indexOf(","));
                }
            }
            // 或者这样也行,对于通过多个代理的情况,第一个IP为客户端真实IP,多个IP按照','分割
            return ipAddress;
        }
    
    }
    

    打印请求日志信息:

  • 相关阅读:
    点击listview 的列头对其item进行自动排序
    将选择的图片显示在listview中,并显示filename,path和type
    【翻译】8 个可以节省时间的 C# 开发相关工具
    【原创】关于乘法运算的新思路
    【翻译】为什么我们要用抽象类?
    【翻译】如何使用 C# 的 BackgroundWorker
    【汉化】DevExpress插件中RichEdit控件的自定义汉化方法
    关于C#日期格式化问题
    C#获取(大陆)身份证基本信息的算法
    C#关于精确年龄的算法(精确到天)
  • 原文地址:https://www.cnblogs.com/daikainan/p/14428140.html
Copyright © 2011-2022 走看看