效果
测试的方法
入参有各种类型的
自定义类注解
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* @类说明: feign调用日志AOP处理
* @Author: 张俊杰 2020年09月05日 14:06
*/
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface FeignLogOutput {
public String value() default "";
}
切面类
/**
* @类说明: 用于拦截feign请求的日志切面类.
* @Author: 张俊杰 2020年09月05日 14:11
*/
@Aspect
@Configuration
public class FeignlLogAspect {
private static final Logger logger = LoggerFactory.getLogger(FeignLogOutput.class);
//切点
@Pointcut("@within(com.datangwealth.um.common.aop.annotation.FeignLogOutput)")
public void pointCut() {
}
@Around("pointCut()")
public Object interceptMethodAround(ProceedingJoinPoint pjd) {
Object result = null;
Signature signature = pjd.getSignature();
String methodName = signature.getName();
String className = signature.getDeclaringTypeName();
String methodNameAndClassName = className + "#" + methodName;
Object[] args = pjd.getArgs(); //获取参数值数组
// 获取参数名字数组
String[] paramNames = ((CodeSignature) pjd.getSignature()).getParameterNames();
//进行循环拼接
StringJoiner stringJoiner = new StringJoiner(" ");
for (int i = 0; i < paramNames.length; i++) {
int count = i + 1;
stringJoiner.add("\r\n参数" + count + ": " + paramNames[i] + "--->" + args[i]);
}
try {
//开始入参写入......
logger.info(" {}方法远程调用入参{}", methodNameAndClassName, stringJoiner.toString());
result = pjd.proceed();
// 正常情况下方法出参在下面代码里面写...
this.resultTypeTransition(result, methodNameAndClassName);
} catch (Throwable e) {
// 方法异常走这里
logger.error("{}方法远程调用异常 ", methodNameAndClassName);
e.printStackTrace();
}
return result;
}
/**
* @功能描述: 结果参数类型转换
* @Author: 张俊杰 2020年09月05日 18:04
*/
private void resultTypeTransition(Object result, String methodNameAndClassName) {
if (result instanceof List) {
List<Object> objects = (List) result;
logger.info("{}方法远程调用出参,返回列表长度为:{} ", methodNameAndClassName, objects.size());
} else if (result instanceof String) {
String objects = (String) result;
logger.info("{}方法远程调用出参,返回参数为:{} ", methodNameAndClassName, objects);
} else if (result instanceof Result) {
Result objects = (Result) result;
logger.info("{}方法远程调用出参,返回code为:{} ,返回的message为{}",
methodNameAndClassName, objects.getCode(), objects.getMessage());
} else {
logger.info("{}方法远程调用出参,返回为:{} ", methodNameAndClassName, result.toString());
}
}