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.joda.time.DateTimeUtils; 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; /** * @author liu pei * @version 1.0.0 * @ClassName AccessLogAspect.java * @Description TODO * @createTime 2023年10月10日 16:15:00 */ @Aspect @Component public class AccessLogAspect { final static Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class); private static final ThreadLocal START_TIME = new ThreadLocal<>(); @Pointcut("execution(public * com.jhxx.*.controller..*.*(..)) || execution(public * com.jhxx.*.controller..*.*(..))") public void invokeLog() { // do something } @Before("invokeLog()") public void doBefore(JoinPoint joinPoint) { // 接收到请求,记录请求内容 ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes(); HttpServletRequest request = attributes.getRequest(); // 记录下请求内容 String args = Arrays.toString(joinPoint.getArgs()); log.info(" Request URL : [{}, {}]", request.getMethod(), request.getRequestURL()); log.info(" Request IP : [{}]", WebUtils.getIP(request)); log.info(" Class : [{}] , Method : [{}()]", joinPoint.getSignature().getDeclaringTypeName(), joinPoint.getSignature().getName()); log.info(" Request Param : {}", args); START_TIME.set(DateTimeUtils.currentTimeMillis()); } @AfterReturning(returning = "ret", pointcut = "invokeLog()") public void doAfterReturning(Object ret) { // 处理完请求,返回内容 String jsonStr = GsonUtils.objToJson(ret); log.info(" Response Body : {}", jsonStr.length() > 500 ? jsonStr.substring(0, 499) : jsonStr); log.info(" Response Time : {} ms ", (DateTimeUtils.currentTimeMillis() - START_TIME.get())); START_TIME.remove(); } }