aop实现controller层请求参数日志输出

直接上代码

package com.taikang.f1.workflow.aop;

import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.CodeSignature;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

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

@Aspect
@Component
@Order(0)
@Slf4j
public class WebLogAspect {

    @Pointcut("execution(public * com.taikang.f1.workflow.controller..*.*(..))")
    public void controllerLog() {
    }

    @Before("controllerLog()")
    public void logBeforeController(JoinPoint joinPoint) {
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();//这个RequestContextHolder是Springmvc提供来获得请求的东西
        assert requestAttributes != null;
        HttpServletRequest request = ((ServletRequestAttributes) requestAttributes).getRequest();

        Map<String, Object> params = getNameAndValue(joinPoint);
        StringBuilder logSb = new StringBuilder();
        for (Map.Entry<String, Object> entry : params.entrySet()) {
            logSb.append(entry.getKey()).append(": ").append(entry.getValue()).append(",");
        }
        // 记录下请求内容
        log.info("URL : " + request.getRequestURL().toString());
        log.info("请求类型 : " + request.getMethod());
        String substring = logSb.substring(0,logSb.length()-1);
        //下面这个getSignature().getDeclaringTypeName()是获取包+类名的   然后后面的joinPoint.getSignature.getName()获取了方法名
        log.info("请求方法 : " + joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName());
        log.info("请求参数 : " + substring);
    }

    /**
     * 获取参数Map集合
     *
     * @param joinPoint
     * @return
     */
    private static Map<String, Object> getNameAndValue(JoinPoint joinPoint) {
        Map<String, Object> param = new HashMap<>();
        Object[] paramValues = joinPoint.getArgs();
        String[] paramNames = ((CodeSignature) joinPoint.getSignature()).getParameterNames();
        for (int i = 0; i < paramNames.length; i++) {
            param.put(paramNames[i], paramValues[i]);
        }
        return param;
    }
}

  

posted @ 2021-02-26 14:01  山沟君  阅读(330)  评论(0)    收藏  举报