1. 定义log注解
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Log {
}
凡是被Log注解修饰的方法,都会打log
2. 定义切面和切点
其中切点要指定Log注解
,打印方法执行前和方法执行后的log
@Component
@Slf4j
@Aspect
public class XXXAspect {
@Autowired
private HttpServletRequest request;
@Pointcut("@annotation(cn.homecredit.itlp.member.voting.common.aspect.Log)")
public void log() {
//do nothing, log() as a pointcut
}
@Before("log()")
public void doBefore(JoinPoint joinPoint) {
log.info("\n\tURL = {},\n\tMETHOD = {},\n\tIP = {},\n\tCLASS METHOD = {},\n\tARGS = {}",
request.getRequestURL(),
request.getMethod(), request.getRemoteAddr(),
joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName(),
joinPoint.getArgs());
}
@AfterReturning(returning = "result", pointcut = "log()")
public void doAfterReturning(HSResult result) {
log.info(result.getData().toString());
}
}
加油儿!