自定义注解实现AOP日志打印

自定义注解
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD})
@Documented
public @interface LogInfo {
String value() default "";
}

AOP实现类
@Aspect
@Configuration
@Slf4j
public class Aop {
// 定义切点Pointcut
// @Pointcut("execution(* com.nike.mpp.controller..*.*(..))")
@Pointcut("@annotation(com.nike.mpp.timer.LogInfo)")
public void executeService() {
}

@Around("executeService()")
public Object doAround(ProceedingJoinPoint pjp) throws Throwable {
RequestAttributes ra = RequestContextHolder.getRequestAttributes();
ServletRequestAttributes sra = (ServletRequestAttributes) ra;
HttpServletRequest request = sra.getRequest();

String url = request.getRequestURL().toString();
String method = request.getMethod();
//String uri = request.getRequestURI();
String queryString = request.getQueryString();
Object[] args = pjp.getArgs();
String params = "";
//获取请求参数集合并进行遍历拼接
if(args.length>0){
if("POST".equals(method)){
Object object = args[0];
Map map = getKeyAndValue(object);
params = JSON.toJSONString(map);
}else if("GET".equals(method)){
params = URLDecoder.decode(queryString,"UTF-8");
}
}

log.info("————————————————————————————————————————————————————");
log.info(getLogValue(pjp));
log.info("请求开始===地址:"+url);
log.info("请求开始===类型:"+method);
log.info("请求开始===参数:"+params);

// result的值就是被拦截方法的返回值
Object result = pjp.proceed();
log.info("请求结束===返回值:" + JSON.toJSON(result));
log.info("————————————————————————————————————————————————————");
return result;
}

public static Map<String, Object> getKeyAndValue(Object obj) {
Map<String, Object> map = new HashMap<>();
// 得到类对象
Class userCla = obj.getClass();
/* 得到类中的所有属性集合 */
Field[] fs = userCla.getDeclaredFields();
for (Field f : fs) {
f.setAccessible(true); // 设置些属性是可以访问的
Object val;
try {
val = f.get(obj);
// 得到此属性的值
map.put(f.getName(), val);// 设置键值
} catch (IllegalArgumentException | IllegalAccessException e) {
e.printStackTrace();
}

}
return map;
}

private String getLogValue(JoinPoint joinPoint) {
MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
Method method = methodSignature.getMethod();

LogInfo logInfo = method.getAnnotation(LogInfo.class);

return logInfo.value();
}
}

使用方式(在Controller使用该注解)
@LogInfo(value = "测试测试,查询版本")
posted @ 2021-12-30 14:18  风吟雪  阅读(83)  评论(0编辑  收藏  举报