自定义注解+切面,环绕通知打印方法日志
一、自定义注解类
public @interface XXXInterface {
}
二、切面类
@Component
@Aspect
public class XXXInterfaceAspect {
private static final Logger US_LOG = LogBuilderFactory.unstructuredLog();
@Pointcut("@annotation(annotation.XXXInterface)")
public void pointCut() {}
@Around("pointCut()")
public Object doAround(ProceedingJoinPoint joinPoint) throws Exception {
XXXResponseDTO result;
Signature signature = joinPoint.getSignature();
MethodSignature methodSignature = (MethodSignature) signature;
//获取目标对象
Object target = joinPoint.getTarget();
//获取目标方法
Method method = target.getClass().getMethod(methodSignature.getName(), methodSignature.getParameterTypes());
//获取方法注解
XXXInterface annotation = method.getAnnotation(XXXInterface .class);
//获取方法参数
Object[] parameterValues = joinPoint.getArgs();
XXXRequestDTO request = (XXXRequestDTO) Arrays.stream(parameterValues)
//过滤继承XXXRequestDTO的类
.filter(XXXRequestDTO.class::isInstance)
.findFirst()
.orElse(null);
//获取请求id
String requestId = Objects.isNull(request) ? null : request.getRequestId();
long start = System.currentTimeMillis();
try {
//方法执行前打印日志
xxx_LOG.info("received request, id: {}, method: {}, info: {}", Objects.isNull(requestId) ? StringUtils.EMPTY : requestId, method.getName(), request);
//执行目标方法
result = (BaseResponseDTO) joinPoint.proceed();
} catch (XXXException pme) {
} catch (Throwable e) {
e.getMessage(), requestId);
}
result.setRequestId(requestId);
result.setResponseDateTime(new Date());
result.setResponseStatus(ResponseStatusEnum.SUCCESS);
if (Objects.isNull(result.getResults())) {
xxx_LOG.info("success handling request, id: {}, cost: {}", Objects.isNull(requestId) ? StringUtils.EMPTY : requestId, System.currentTimeMillis() - start);
} else {
int resCount = 0;
if (result.getResults() instanceof List) {
resCount = ( (List>) result.getResults()).size();
} else if (result.getResults() instanceof Map) {
resCount = ( (Map, ?>) result.getResults()).size();
}
//方法执行后打印日志
xxx_LOG.info();
}
return result;
}