SpringBoot obtains @RequestBody parameters through aop and records them in the log

table of Contents

I. Introduction

2. Effect display

Third, the source code of the aspect class

Four, maven dependency


I. Introduction

        Obtaining the body parameter through request.getInputStream(); is more complicated to implement because the input stream can only be used once. The body parameter can be obtained by using the point.getArgs() method in Spring's aop, which is less intrusive to the source code and is preferred.

Reference: Get requestbody parameters in spring boot aop

2. Effect display

2020-07-23 14:19:59.124 |-INFO  [http-nio-8080-exec-1] com.asyf.demo.config.AopLog [56] -| 
【request_id】:6181ae98c4404481a522eeb8d2508f17
【请求 URL】:http://localhost:8080/test3
【请求 IP】:0:0:0:0:0:0:0:1
【请求类名】:com.asyf.demo.controller.DemoController【请求方法名】:test3
【body】:[{"name":"lisi","id":1}]
【请求参数】:{}
2020-07-23 14:19:59.140 |-INFO  [http-nio-8080-exec-1] com.asyf.demo.config.AopLog [84] -| 
【request_id】:6181ae98c4404481a522eeb8d2508f17
【返回值】:获取body传参的参数测试 - {"id":1,"name":"lisi"}
2020-07-23 14:19:59.154 |-INFO  [http-nio-8080-exec-1] com.asyf.demo.config.AopLog [108] -| 
【request_id】:6181ae98c4404481a522eeb8d2508f17
【请求耗时】:17毫秒
【浏览器类型】:UNKNOWN
【操作系统】:UNKNOWN
【原始User-Agent】:PostmanRuntime/7.26.1

 

Third, the source code of the aspect class

package com.asyf.demo.config;

import cn.hutool.core.util.IdUtil;
import cn.hutool.json.JSONUtil;
import eu.bitwalker.useragentutils.UserAgent;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;
import java.util.Objects;

@Aspect
@Component
public class AopLog {

    private static final Logger log = LoggerFactory.getLogger(AopLog.class);

    private static final String START_TIME = "request-start";

    private static final String REQUEST_ID = "request_id";

    /**
     * 切入点
     */
    @Pointcut("execution(public * com..controller.*Controller.*(..))")
    public void log() {

    }

    /**
     * 前置操作
     *
     * @param point 切入点
     */
    @Before("log()")
    public void beforeLog(JoinPoint point) {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = Objects.requireNonNull(attributes).getRequest();
        Map<String, String[]> parameterMap = request.getParameterMap();
        StringBuffer sb = new StringBuffer();
        String requestId = IdUtil.simpleUUID();
        sb.append("\n【request_id】:").append(requestId);
        sb.append("\n【请求 URL】:").append(request.getRequestURL());
        sb.append("\n【请求 IP】:").append(getIp(request));
        sb.append("\n【请求类名】:").append(point.getSignature().getDeclaringTypeName());
        sb.append("【请求方法名】:").append(point.getSignature().getName());
        sb.append("\n【body】:").append(JSONUtil.toJsonStr(point.getArgs()));
        sb.append("\n【请求参数】:").append(JSONUtil.toJsonStr(parameterMap));
        log.info(sb.toString());

//        log.info("【请求 URL】:{}", request.getRequestURL());
//        log.info("【请求 IP】:{}", request.getRemoteAddr());
//        log.info("【请求类名】:{},【请求方法名】:{}", point.getSignature().getDeclaringTypeName(), point.getSignature().getName());
//        log.info("【body】:{},", JSONUtil.toJsonStr(point.getArgs()));
//        log.info("【请求参数】:{},", JSONUtil.toJsonStr(parameterMap));
        Long start = System.currentTimeMillis();
        request.setAttribute(START_TIME, start);
        request.setAttribute(REQUEST_ID, requestId);
    }

    /**
     * 环绕操作
     *
     * @param point 切入点
     * @return 原方法返回值
     * @throws Throwable 异常信息
     */
    @Around("log()")
    public Object aroundLog(ProceedingJoinPoint point) throws Throwable {
        Object result = point.proceed();
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = Objects.requireNonNull(attributes).getRequest();
        String requestId = (String) request.getAttribute(REQUEST_ID);
        StringBuffer sb = new StringBuffer();
        sb.append("\n【request_id】:").append(requestId);
        sb.append("\n【返回值】:").append(JSONUtil.toJsonStr(result));
        log.info(sb.toString());
//        log.info("\n【request_id】:" + requestId + "\n【返回值】:{}", JSONUtil.toJsonStr(result));
        return result;
    }

    /**
     * 后置操作
     */
    @AfterReturning("log()")
    public void afterReturning() {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = Objects.requireNonNull(attributes).getRequest();
        String requestId = (String) request.getAttribute(REQUEST_ID);
        StringBuffer sb = new StringBuffer();
        sb.append("\n【request_id】:").append(requestId);
        Long start = (Long) request.getAttribute(START_TIME);
        Long end = System.currentTimeMillis();
        sb.append("\n【请求耗时】:").append((end - start)).append("毫秒");

        String header = request.getHeader("User-Agent");
        UserAgent userAgent = UserAgent.parseUserAgentString(header);
        sb.append("\n【浏览器类型】:").append(userAgent.getBrowser().toString());
        sb.append("\n【操作系统】:").append(userAgent.getOperatingSystem());
        sb.append("\n【原始User-Agent】:").append(header);
        log.info(sb.toString());
//        log.info("【请求耗时】:{}毫秒", end - start);
//        log.info("【浏览器类型】:{},【操作系统】:{},【原始User-Agent】:{}", userAgent.getBrowser().toString(), userAgent.getOperatingSystem().toString(), header);
    }

    private String getIp(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return ip;
    }

}

Four, maven dependency

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-aop</artifactId>
        </dependency>   
     
        <dependency>
            <groupId>cn.hutool</groupId>
            <artifactId>hutool-all</artifactId>
            <version>5.2.5</version>
        </dependency>

        <dependency>
            <groupId>eu.bitwalker</groupId>
            <artifactId>UserAgentUtils</artifactId>
            <version>1.21</version>
        </dependency>

 

Guess you like

Origin blog.csdn.net/cs373616511/article/details/107535480