SpringBoot AOP记录请求参数,操作日志


ControllerLogAspect.java

import com.alibaba.fastjson.JSON;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
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.io.BufferedReader;
import java.util.Map;

/**
 * @Description:AOP切入点记录操作日志
 * @Author:chenyanbin
 * @Date:2021/3/19 下午11:30
 * @Versiion:1.0
 */
@Aspect
@Order(5)
@Component
public class ControllerLogAspect {
    @Autowired
    LogTask logTask;

    //切入点表达式
    @Pointcut("execution(public * com.ybchen.service.trace.controller..*.*(..))")
    public void controllerLog() {
    }

    /**
     * 进入controller之前,拿请求参数
     * @param joinPoint
     * @throws Throwable
     */
    @Before("controllerLog()")
    public void doBefore(JoinPoint joinPoint) throws Throwable {

        // 接收到请求,记录请求内容
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        String params = null;
        String ip = request.getRemoteAddr();
        // 只记录post方法
        if ("POST".equals(request.getMethod())) {
            // 记录下请求内容
            System.out.println("请求URL : " + request.getRequestURL());
            System.out.println("请求IP : " + request.getRemoteAddr());
            System.out.println("请求方法 : " + joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName());

            // 获取参数, 只取自定义的参数, 自带的HttpServletRequest, HttpServletResponse不管
            BufferedReader br = request.getReader();
            String str, wholeStr = "";
            while ((str = br.readLine()) != null) {
                wholeStr += str;
            }
            StringBuilder stringBuilder = new StringBuilder();
            if ("".equals(wholeStr)) {
                System.out.println("不是json提交,重新获取post请求参数");
                Map<String, String[]> parameterMap = request.getParameterMap();
                parameterMap.forEach((k, v) -> {
                    if (v != null && v.length > 0) {
                        for (int i = 0; i < v.length; i++) {
                            stringBuilder.append(v[i]);
                        }
                    }
                    System.out.println("post请求,key= " + k + " ,value= " + stringBuilder.toString());
                });
            } else {
                System.out.println("post请求参数:" + wholeStr);
                params = wholeStr;
            }
            params = stringBuilder.toString();
        }
        if ("GET".equals(request.getMethod())) {
            System.out.println("请求URL : " + request.getRequestURL());
            System.out.println("请求IP : " + request.getRemoteAddr());
            System.out.println("请求参数:" + request.getQueryString());
            params = request.getQueryString();
        }
        logTask.addLog(ip, params);
    }

    /**
     * 接口执行之后,获取响应结果
     * @param ret
     * @throws Throwable
     */
    @AfterReturning(returning = "ret", pointcut = "controllerLog()")
    public void doAfterReturning(Object ret) throws Throwable {
        // 处理完请求,返回内容
        System.out.println("返回 : " + JSON.toJSONString(ret));
    }
}

LogTask.java

import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.io.IOException;

/**
 * @Description:记录日志
 * @Author:chenyanbin
 * @Date:2021/3/19 下午7:08
 * @Versiion:1.0
 */
@Service
public class LogTask {
    @Async
    public void addLog(String ip, String params) throws IOException {
        System.out.println("异步保存日志,ip=" + ip + ",参数值:" + params);
    }
}

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM