JDK版本
1.8+
POM依赖
<!-- AOP -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
<!-- lombok -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<!-- fastjson-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
</dependency>
代码
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
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.springframework.stereotype.Component;
import java.time.Duration;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
@Slf4j
@Aspect
@Component
public class LogAspect {
@Pointcut("execution(* com.lh.controller..*.*(..))")
public void logPointCut() {
}
@Around("logPointCut()")
public Object SystemLog(ProceedingJoinPoint joinPoint) throws Throwable {
MethodSignature signature = (MethodSignature) joinPoint.getSignature();
//请求的 类名、方法名
String className = joinPoint.getTarget().getClass().getSimpleName();
String methodName = signature.getName();
//请求的参数
Object[] args = joinPoint.getArgs();
List<Object> list = new ArrayList<>();
try {
list.addAll(Arrays.asList(args));
} catch (Exception ignored) {
}
log.info("[LogAspect before] className : {}, methodName : {}, params: {} ",
className, methodName, JSON.toJSONString(list));
LocalDateTime start = LocalDateTime.now();
Object res = joinPoint.proceed();
Duration between = Duration.between(start, LocalDateTime.now());
log.info("[LogAspect after] methodName : {}, use time(Millis) : {}", methodName, between.toMillis());
return res;
}
}