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