本文参考:https://mp.weixin.qq.com/s/JThls6pYtWoQYjac_chSUQ。欢迎大家移步看原文,更加的全面。本文只在切点前记录log。
首先加入依赖包:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.8.6</version>
</dependency>
然后写个自定义注解:
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
@Documented
public @interface WebLog {
String description() default "";
}
配置切点和定义before方法
@Aspect
@Component
public class WebLogAspect {
/**
* 定义切点
* @author Qingcheng Wang
* @date 2020/1/14 0014
* @param
* @return
*/
@Pointcut("@annotation(com.weblog.demo.annotations.WebLog)") //这里是自定义注解的全路径
public void webLog() {
}
@Before("webLog()")
public void doBefore(JoinPoint joinPoint) {
LogVO logVO = getAspectLogDescription(joinPoint);
LogFactory.getBusinessLog().info(logVO.toString());
}
private LogVO getAspectLogDescription(JoinPoint joinPoint) {
Class targetClass = joinPoint.getTarget().getClass();
String methodName = joinPoint.getSignature().getName();
Object[] args = joinPoint.getArgs();
Method[] methods = targetClass.getMethods();
StringBuilder description = new StringBuilder();
Optional.ofNullable(methods).ifPresent(ms ->
Arrays.stream(ms).filter(m -> m.getName() != null && m.getName().equals(methodName)).findFirst()
.ifPresent(m -> {
Class[] clazzes = m.getParameterTypes();
if (clazzes.length == args.length) {
description.append(m.getAnnotation(WebLog.class).description());
}
}));
LogVO logVO = new LogVO();
logVO.setTarget(targetClass.getName());
logVO.setMethod(methodName);
logVO.setDescription(description.toString());
logVO.setArguments(new Gson().toJson(args));
return logVO;
}
}
这里我用了LogVO类封装日志信息。
public class LogVO {
/**
* @description 类名
*/
private String target;
/**
* @description 方法名
*/
private String method;
/**
* @description 方法参数
*/
private String arguments;
/**
* @description API描述
*/
private String description;
//省略get/set方法
@Override
public String toString() {
return "LogVO{" + "target='" + target + '\'' + ", method='" + method + '\'' + ", arguments='" + arguments + '\'' + ", description='" + description + '\'' + '}';
}
}
到此完成,因为记录了参数信息,所以类似登录接口记录了密码的方法不建议使用。