使用 spring aop 打印controller日志信息(包括 controller#handler 方法的请求参数名和参数值)
目标:打印某个controller#handler方法的带有 @RequestParam注解的参数名(注解的value值)和参数值
package com.sanlian.bigdata.aop; import com.guanxin.base.annotation.RequestParam; import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.annotation.Around; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Pointcut; import org.aspectj.lang.reflect.MethodSignature; 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.lang.annotation.Annotation; import java.util.LinkedHashMap; import java.util.Map; /** * 自定义切面类: 打印 controller 参数和执行情况 * * @Auther: oy * @Date: 2020/8/4 10:55 */ @Component @Aspect public class LoggerAspect { Logger logger = LoggerFactory.getLogger(LoggerAspect.class); // 定义公共切入点 @Pointcut("execution(public * com.sanlian.bigdata.ctrl.*.*(..))") public void webLog() { } @Around("webLog()") public Object around(ProceedingJoinPoint pjp) throws Throwable { long startTime = System.currentTimeMillis(); Object result = pjp.proceed(); long time = System.currentTimeMillis() - startTime; // 接收到请求,记录请求内容 ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes(); HttpServletRequest request = attributes.getRequest(); // 获取handler的参数(不包括 request 和 response) // List<Object> logArgs = Arrays.stream(pjp.getArgs()) // .filter(arg -> (!(arg instanceof HttpServletRequest) && !(arg instanceof HttpServletResponse))) // .collect(Collectors.toList()); // 记录下请求内容 logger.info("URL : " + request.getRequestURL().toString() + "=============="); logger.info("HTTP_METHOD : " + request.getMethod()); logger.info("IP : " + request.getRemoteAddr()); logger.info("CLASS_METHOD : " + pjp.getSignature().getDeclaringTypeName() + "." + pjp.getSignature().getName()); // 获取所有参数上的注解 MethodSignature signature = (MethodSignature) pjp.getSignature(); Annotation[][] parameterAnnotations = signature.getMethod().getParameterAnnotations(); Map<String, Object> params = new LinkedHashMap<>(); int index = 0; for (Annotation[] annotations : parameterAnnotations) { for (Annotation anno : annotations) { //System.out.println(anno.getClass()); // class com.sun.proxy.$Proxy149 if (anno instanceof RequestParam) { params.put(((RequestParam) anno).value(), pjp.getArgs()[index++]); } } } logger.info("params : " + params); //logger.info("ARGS : " + logArgs); logger.info("handler执行时长 : " + time + " ms ========================================="); return result; } }
打印结果:
---
posted on 2020-08-04 16:18 wenbin_ouyang 阅读(1397) 评论(0) 编辑 收藏 举报