项目中需要通过日志记录应用的上下游调用信息。
具体实现
通过切面来打印接口的调用信息
代码:
import lombok.extern.slf4j.Slf4j;
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.springframework.stereotype.Component;
import java.util.Arrays;
@Aspect
@Component
@Slf4j
public class LogRecodeAspect {
@Pointcut("execution( * com.hx.order.center.api..*.*(..))")
public void apiLog() {
}
@Pointcut("execution( * com.hx.order.center.integration..*.*(..))")
public void integrationLog() {
}
@Around(value = "apiLog()")
public Object apiLog(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
String model = "api";
return recordLog(proceedingJoinPoint, model);
}
@Around(value = "integrationLog()")
public Object integrationLog(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
String model = "integration";
return recordLog(proceedingJoinPoint, model);
}
public Object recordLog(ProceedingJoinPoint proceedingJoinPoint, String model) throws Throwable {
long startTime = System.currentTimeMillis();
String declaringTypeName = proceedingJoinPoint.getSignature().getDeclaringTypeName();
String simpleName = declaringTypeName.substring(declaringTypeName.lastIndexOf('.') + 1);
String path = simpleName + "." + proceedingJoinPoint.getSignature().getName();
//发生异常后,手动捕获后抛出,由全局异常捕获统一处理
try {
Object object = proceedingJoinPoint.proceed();
long time = System.currentTimeMillis() - startTime;
String info = String.format("model:%s path:%s request:%s response:%s time:%dms",
model, path, Arrays.toString(proceedingJoinPoint.getArgs()), object, time);
log.info(info);
return object;
} catch (Throwable e) {
long time = System.currentTimeMillis() - startTime;
String error = String.format("model:%s path:%s request:%s exception:%s time:%dms",
model, path, Arrays.toString(proceedingJoinPoint.getArgs()), e, time);
log.error(error);
throw e;
}
}
}
如有问题,请留言!


