1.指定切面类:一般通过注解进行
2.指定切点:
3.监听
创造切点
@Retention(RetentionPolicy.RUNTIME) // 指定运行时
@Target({ElementType.METHOD}) // 可以加在方法上
public @interface SystemLog {
// 可以向注解里面传递参数 例如 :businessName = “更新用户信息”
String businessName() ;
}
RetentionPolicy:源码
指定切面类
@Component
@Aspect // 标记是切面类
@Slf4j
public class LogAspect {
// 确定切点 , 加上 @SystemLog注解的全部是切点
@Pointcut("@annotation(com.sangeng.annotation.SystemLog)")
public void pt(){
}
//环绕通知 ,在之前之后 都会打印
// ProceedingJoinPoint :获取目标 **方法** 的信息
@Around("pt()")
public void printLog(ProceedingJoinPoint joinPoint) throws Throwable {
Object ret;
try {
// 运行之前打印信息
handleBefore(joinPoint) ;
// joinPoint.proceed(): 获取对应方法的返回结果
Object proceed = joinPoint.proceed();
// 运行之后打印信息
handleAfter(proceed) ;
}finally {
log.info("--------END---------"+System.lineSeparator());
}
}
private void handleAfter(Object ret) {
log.info("Response : {}", JSON.toJSONString(ret));
}
// ProceedingJoinPoint 是一个接口 !!
private void handleBefore(ProceedingJoinPoint joinPoint) {
// 获取requet 从request中获取 request.getRequestURL() ,RequestContextHolder是保存在本地线程之中的 threadlocal
ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
HttpServletRequest request = requestAttributes.getRequest();
//
SystemLog systemLog = getSystemLog(joinPoint) ;
log.info("=======Start=======");
// 打印请求 URL
log.info("URL : {}",request.getRequestURL());
// 打印描述信息
log.info("BusinessName : {}",systemLog.businessName() );
// 打印 Http method
log.info("HTTP Method : {}", request.getMethod());
// joinPoint 打印调用 controller 的全路径以及执行方法
log.info("Class Method : {}.{}", joinPoint.getSignature().getDeclaringTypeName(),
((MethodSignature) joinPoint.getSignature()).getName());
// 打印请求的 IP
log.info("IP : {}",request.getRemoteHost());
// joinPoint 打印请求入参
log.info("Request Args : {}", JSON.toJSONString(joinPoint.getArgs()));
// 打印出参
// 结束后换行 System.lineSeparator():系统的换行符 linux 和windows的不一样
log.info("=======End=======" + System.lineSeparator());
}
//获取注解信息
private SystemLog getSystemLog(ProceedingJoinPoint joinPoint) {
MethodSignature signature = (MethodSignature) joinPoint.getSignature();
return signature.getMethod().getAnnotation(SystemLog.class);
}
}
ProceedingJoinPoint 实现类的 源码