package com.sleep.demo.intercepter; import com.alibaba.fastjson.JSONObject; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.ArrayUtils; 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.springframework.stereotype.Component; import org.springframework.web.context.request.RequestContextHolder; import org.springframework.web.context.request.ServletRequestAttributes; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; import java.util.stream.Stream; @Slf4j @Aspect @Component public class ControllerLogAspect { @Pointcut("execution(* com.sleep.demo.controller..*.*(..))") public void pointCut() { } @Around(value = "pointCut()") public Object doAuthMethodInterrupt(ProceedingJoinPoint point) { ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes(); HttpServletRequest request = attributes.getRequest(); String methodName = point.getSignature().getName(); // 入参 Object[] paramArr = point.getArgs(); //序列化时过滤掉request和response List<Object> logArgs = streamOf(paramArr) .filter(arg -> (!(arg instanceof HttpServletRequest) && !(arg instanceof HttpServletResponse ))) .collect(Collectors.toList()); // 入参打印 log.info(">>>>>>>>>>>> Method:{} , path={} ,Param:{}" , methodName, request.getRequestURI(), JSONObject.toJSONString(logArgs)); try { long currentTimeStampBegin = System.currentTimeMillis(); Object obj = point.proceed(); long diff = System.currentTimeMillis() - currentTimeStampBegin; // 出参打印 log.info("<<<<<<<<<<<< method:{} , Response:{} ,time:{}ms", methodName, JSONObject.toJSONString(obj), diff); return obj; } catch (Throwable e) { log.error("<<<<<<<<<<<< method:{},REQUEST_ERROR_MSG:{}", methodName, e.getMessage()); // throw new RuntimeException(e); e.printStackTrace(); return 500; } } public static <T> Stream<T> streamOf(T[] array) { return ArrayUtils.isEmpty(array) ? Stream.empty() : Arrays.stream(array); } }
需要有spring aop的支持
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-aop</artifactId> </dependency>
标签:java,request,springframework,util,controller,vop,import,org From: https://www.cnblogs.com/niun/p/17015387.html