package com.agentdriving.user.core.common.aspect;
|
|
import com.agentdriving.user.core.common.annotion.ServiceLog;
|
import com.alibaba.fastjson.JSONObject;
|
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.slf4j.Logger;
|
import org.slf4j.LoggerFactory;
|
import org.springframework.stereotype.Component;
|
|
import java.lang.reflect.Method;
|
import java.lang.reflect.Parameter;
|
|
@Aspect
|
@Component
|
public class ServiceLogAspect {
|
|
Logger logger = LoggerFactory.getLogger("ServiceLog");
|
|
/**
|
* //切面点为标记了@ServiceLog注解的方法
|
*/
|
@Pointcut("@annotation(com.agentdriving.user.core.common.annotion.ServiceLog)")
|
public void serviceLog(){
|
}
|
|
|
//环绕通知
|
@Around("serviceLog()")
|
@SuppressWarnings("unchecked")
|
public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
|
try {
|
long starTime = System.currentTimeMillis();
|
//通过反射获取被调用方法的Class
|
Class type = joinPoint.getSignature().getDeclaringType();
|
//获取类名
|
String typeName = type.getSimpleName();
|
//方法名
|
String methodName = joinPoint.getSignature().getName();
|
//获取参数列表
|
Object[] args = joinPoint.getArgs();
|
//参数Class的数组
|
Class[] clazz = new Class[args.length];
|
for (int i = 0; i < args.length; i++) {
|
clazz[i] = args[i].getClass();
|
}
|
//通过反射获取调用的方法method
|
Method method = type.getMethod(methodName, clazz);
|
ServiceLog serviceLog = method.getAnnotation(ServiceLog.class);
|
//获取方法的参数
|
Parameter[] parameters = method.getParameters();
|
JSONObject jsonObject = new JSONObject();
|
for (int i = 0; i < parameters.length; i++) {
|
Parameter parameter = parameters[i];
|
String name = parameter.getName();
|
jsonObject.put(name, args[i]);
|
}
|
//执行结果
|
//执行目标方法,获取执行结果
|
Object res = joinPoint.proceed();
|
logger.debug("调用{}.{}方法成功\n" +
|
"接口名称:{}\n" +
|
"接口地址:{}\n" +
|
"耗时:{}ms\n" +
|
"参数为:{}\n" +
|
"返回结果:{}", typeName, methodName, serviceLog.name(), serviceLog.url(),
|
(System.currentTimeMillis() - starTime), jsonObject.toJSONString(), JSONObject.toJSONString(res));
|
}catch (Exception e){
|
e.printStackTrace();
|
}
|
return joinPoint.proceed();
|
}
|
}
|