首先创建annotation.SystemLog类:
package com.gjh.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target(ElementType.METHOD) //加在什么东西上
@Retention(RetentionPolicy.RUNTIME) //什么时候
public @interface SystemLog {
String BusinessName(); //会以注解方式用在接口上
}
然后创建aspect.LogAspect:
package com.gjh.aspect;
import com.alibaba.fastjson.JSON;
import com.gjh.annotation.SystemLog;
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 org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest;
@Component
@Aspect
@Slf4j
public class LogAspect {
@Pointcut("@annotation(com.gjh.annotation.SystemLog)")
public void pt(){
}
@Around("pt()")
public Object printLog(ProceedingJoinPoint joinPoint) throws Throwable {
Object ret;
try {
handleBefore(joinPoint);
ret = joinPoint.proceed();
handleAfter(ret);
} finally {
// 结束后换行
log.info("=======End=======" + System.lineSeparator());
}
return ret;
}
//切入点之前运行
private void handleBefore(ProceedingJoinPoint joinPoint) {
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());
// 打印调用 controller 的全路径以及执行方法
log.info("Class Method : {}.{}",joinPoint.getSignature().getDeclaringTypeName(),((MethodSignature)joinPoint.getSignature()).getName());
// 打印请求的 IP
log.info("IP : {}",request.getRemoteHost());
// 打印请求入参
log.info("Request Args : {}", JSON.toJSONString(joinPoint.getArgs()));
}
private SystemLog getSystemLog(ProceedingJoinPoint joinPoint) {
MethodSignature methodSignature =(MethodSignature) joinPoint.getSignature();
SystemLog systemLog = methodSignature.getMethod().getAnnotation(SystemLog.class);
return systemLog;
}
//切入点之后运行
private void handleAfter(Object ret) {
// 打印出参
log.info("Response : {}", JSON.toJSONString(ret));
}
}
最后,在需要的接口上使用注解:
@SystemLog(BusinessName = "更新用户信息")
例如我用在了:
@PutMapping("/userInfo")
@Operation(tags = "修改个人信息")
@SystemLog(BusinessName = "更新用户信息") //AOP
public ResponseResult updateUserInfo(@RequestBody UserInfoDTO userInfoDTO){
return ResponseResult.okResult(userservice.UpdateUserInfo(userInfoDTO));
}
重启测试:
当我们进行修改个人信息之后: