依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
切面定义
@Slf4j
@Aspect
@Component
public class WebLogAspect {
@Autowired
private ObjectMapper mapper;
@Pointcut("execution(public * com.controller..*.*(..))")
public void webLog() { }
@Before("webLog()")
public void doBefore(JoinPoint joinPoint) throws Throwable {
log.debug("Request Begin ... ");
ServletRequestAttributes attributes = (ServletRequestAttributes)RequestContextHolder.getRequestAttributes();
HttpServletRequest request = attributes.getRequest();
log.debug("URL: [{}]", request.getRequestURL().toString());
log.debug("HTTP Method: [{}]", request.getMethod());
log.debug("Class Method: [{}].[{}]",joinPoint.getSignature().getDeclaringTypeName(),joinPoint.getSignature().getName());
String requestArgs = mapper.writeValueAsString(joinPoint.getArgs());
log.debug("Request Args: [{}]", requestArgs);
}
@After("webLog()")
public void doAfter() throws Throwable {
log.debug("Request Done ... ");
}
@Around("webLog()")
public Object doAround(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
StopWatch sw = StopWatch.createStarted();
Object result = proceedingJoinPoint.proceed();
sw.stop();
log.debug("Request Time {} ms", sw.getTime(TimeUnit.MILLISECONDS));
return result;
}
}