一、预期效果
对所有@RequestMapping注解的接口全部记录接口调用情况并记入日志。
二、实现代码
tips: 这里使用了Lombok的@Slf4j实现日志
@Aspect
@Component
@Slf4j
public class ReportApiCallTimesAspect {
/*调用次数记录前缀,方便根据前缀获取所有接口的数据*/
public static final String WEB_API_CALL_COUNT = "web_api_call_count";
/*时间格式*/
private static String TIME_FORMAT = "yyyy-MM-dd HH:mm:ss";
@Pointcut(value = "@annotation(org.springframework.web.bind.annotation.RequestMapping)")
public void reportCallTimes(){
}
@Before(value = "reportCallTimes()")
public void before(JoinPoint joinPoint){
try {
// 获取类名及方法名,拼接为 类名.方法名, 其中类名不包含所在包
MethodSignature signature = (MethodSignature) joinPoint.getSignature();
String className = signature.getDeclaringType().getSimpleName();
Method method = signature.getMethod();
RequestMapping annotation = method.getAnnotation(RequestMapping.class);
String apiUrl = "";
String httpMethod = "";
if (annotation != null){
apiUrl = ArrayUtils.isNotEmpty(annotation.value()) ? annotation.value()[0] : "";
httpMethod = ArrayUtils.isNotEmpty(annotation.method()) ? annotation.method()[0].name() : "";
}
// 记录格式, web_api_call_count_类名_请求地址_请求方法 , url地址和请求方法可以为空,即空字符串,添加固定前缀
log.info(this.WEB_API_CALL_COUNT + "_" + className + "_" + apiUrl + "_" + httpMethod);
}catch (Exception e){
log.error("ReportApiCallTimesAspect,@Before error.");
}finally {
recordInfo2Log();
}
}
private void recordInfo2Log(){
// 获取请求
HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
// 获取 URL
String url = request.getRequestURL().toString();
// 请求方法
String method = request.getMethod();
// 获取调用者IP
String ip = IpUtil.getClientRealIP(request);
// 获取调用时间
String date = DateFormatUtils.format(new Date(),TIME_FORMAT);
log.info("接口请求:" + url + ",请求方法:" + method + ",调用者IP:" + ip + ",请求时间:" + date);
}
}