1. 引入依赖
org.springframework.boot
spring-boot-starter-aop
2. 写切面
切面类需要加@Aspect和@Component注解
package com.test.demo.aspect;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
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 cn.hutool.core.date.DateUtil;
import cn.hutool.extra.servlet.ServletUtil;
import cn.hutool.json.JSONUtil;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
@Aspect
@Component
@Slf4j
public class LogPrintAspect {
@Pointcut("execution(public * com.test.demo.*.*(..))")
public void getMethodName() {
}
@Pointcut("within(com.test.demo..*) && @within(org.springframework.web.bind.annotation.RestController)")
public void printParams() {
}
/**
* 打印请求参数
* @param joinPoint
*/
@Before(value = "printParams()")
public void paramsLog(JoinPoint joinPoint) {
ServletRequestAttributes requestAttributes =
(ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
HttpServletRequest request = requestAttributes.getRequest();
Class> targetClass = joinPoint.getTarget().getClass();
if (targetClass.isAnnotationPresent(Api.class)) {
Api swaggerApi = (Api) targetClass.getDeclaredAnnotation(Api.class);
log.info("模块的中文汉字 {} , {}", swaggerApi.value(), swaggerApi.tags()[0]);
}
log.info("sign -- {}", joinPoint.getSignature());
log.info("请求地址:" + request.getRequestURL().toString());
log.info("请求方式:" + request.getMethod());
Map m = ServletUtil.getParamMap(request);
log.info("请求参数:{}", m);
}
/**
* 打印响应内容
* @param o
*/
@AfterReturning(returning = "o", pointcut = "printParams()")
public void methodAfterReturing(Object o) {
log.info(JSONUtil.parse(o).toJSONString(1));
}
/**
* 打印方法耗时
* @param joinPoint
* @return
* @throws Throwable
*/
@Around("printParams()")
public Object around(ProceedingJoinPoint joinPoint) throws Throwable{
long startTime = DateUtil.current(false);
log.info("执行方法:{},开始时间:{}" , joinPoint.getSignature().getName() , startTime);
Object result = joinPoint.proceed();
long endTime= DateUtil.current(false);
log.info("执行方法:{},结束时间:{} , 用时:{} 毫秒 , " , joinPoint.getSignature().getName() , endTime, endTime-startTime);
return result ;
}
}