- 背景描述
- 原料
- 代码开发思路
- 代码
- 效果
- 备注
- 参考内容
目前本人负责一个web项目,该项目为兄弟小组提供接口,供其他小组使用。 公司希望能够及时监控到每个接口的报错。以便在客户或同事提出bug之前将其解决。
原料spring web项目,restful风格接口。
代码开发思路有两个思路,
第一个思路是用拦截器来拦截所有接口的返回responseObject,获取其中的resultCode,用以判断接口是否出现异常;
先是实践第一个思路中从httpServletResponse中获取返回字段,后面发现要写的代码量比较多。具体思路大概是过滤器+ 代理HttpServletResponseWrapper,来拿到返回字段。实现逻辑可以参考这篇博客https://blog.csdn.net/KokJuis/article/details/77371324 。
更改其中的加密逻辑来实现你自己的目的了。
第二个是利用切面工程,将所有controller目录下的类都切一下,如果出现异常,就通知一下。这篇文章具体介绍第二个思路,也就是用切面工程来实现监控接口。
具体思路就是切面加通知,简单直接。
代码
@Aspect
@Component
@Order(Integer.MIN_VALUE)
public class MyAspect {
@Autowired
private UserService userService;
private static Logger log = (Logger) LogManager.getLogger(MyAspect.class.getName());
@Around("execution(* com.xxx.controller..*Controller.*(..))")
public Object recordTimeLog(ProceedingJoinPoint joinPoint) throws Throwable {
// 记录开始时间
long begin = System.currentTimeMillis();
log.info("类信息:{}", joinPoint.getTarget().getClass());
log.info("方法名:{}", joinPoint.getSignature().getName());
// 获得request对象
RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
ServletRequestAttributes sra = (ServletRequestAttributes) requestAttributes;
//拿到想要的httpSxxxRequest
HttpServletRequest req = sra.getRequest();
log.info("请求地址: {}",req.getRequestURI());
log.info("请求设备: {}", req.getHeader("user-agent"));
// 获得参数,并检查是否为实例
Object[] args = joinPoint.getArgs();
if (args!=null && args.length>0){
for (int i = 0; i < args.length; i++) {
if (args[i] instanceof HttpServletRequest || args[i] instanceof HttpServletResponse)
continue;
log.info("参数:" + ( args[i]==null? "": new Gson().toJson(args[i])));
}
}
// 执行目标 service
Object result = joinPoint.proceed();
JSONObject jsonObject = (JSONObject) JSONObject.toJSON(result);
log.info("响应:" + new Gson().toJson(result));
String code = jsonObject.getString("resultCode");
if(!code.equals("0")){
System.out.println("请求失败,插入访问接口异常表");
String date = DateUtil.getCurrentDate();
String time = DateUtil.getNow(DateUtil.PATTERN_TIME_HH);
userService.insertException(code,date,time,req.getRequestURI());
}
// 记录结束时间
long end = System.currentTimeMillis();
long time = end - begin;
log.info("执行时间:{} 毫秒", time);
return result;
}
}
这段代码就是我的切面了。用了@Around环绕通知,不明白的可以看下去搜搜AOP切面的知识。
最核心的逻辑就是在里面拿请求和返回里面的数据。然后判断就可以了。
这个joinPoint很有用,可以在里面看到切点的各种信息,有兴趣可以dubug自己试试。
如下图
接口异常表



