背景:
系统开发测试过程中,常需要关注请求参数和返回参数,以及方法运行时长(使用filter也可实现)。
基于springAop注解实现
@Aspect
@Component
public class HttpAspect {
//定义在controller包和所有子包里的任意类的public方法的执行
@Pointcut("execution(public * com.cb.springboottest.controller..*.*(..))")
public void cut(){
}
@Before("cut()")
public void doBefore(JoinPoint joinPoint){
ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
HttpServletRequest request = attributes.getRequest();
log.info("机器地址={}",request.getRemoteAddr());
log.info("接口url={}",request.getRequestURI());
log.info("接口参数={}",joinPoint.getArgs());
}
@After("cut()")
public void doAfter(){}
@Around("cut()")
public Object timeAround(ProceedingJoinPoint joinPoint) throws Throwable {
long startTime;
long endTime;
Object obj;
// 获取开始时间
startTime = System.currentTimeMillis();
// 获取返回结果集
obj = joinPoint.proceed(joinPoint.getArgs());
// 获取方法执行时间
endTime= System.currentTimeMillis() - startTime;
String classAndMethod = joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName();
log.info("执行 " + classAndMethod + " 耗时为:" + endTime+ "ms");
return obj;
}
@AfterReturning(returning = "obj",pointcut = "cut()")
public void doAfterReturning(Object obj){
log.info("接口响应={}", JSON.toJSONString(obj));
}
}
请求结果演示
2020-04-13 21:03:47.224 [http-nio-9905-exec-1] INFO com.cb.springboottest.aspect.HttpAspect - 机器地址=0:0:0:0:0:0:0:1
2020-04-13 21:03:47.225 [http-nio-9905-exec-1] INFO com.cb.springboottest.aspect.HttpAspect - 接口url=/test/Bill
2020-04-13 21:03:47.225 [http-nio-9905-exec-1] INFO com.cb.springboottest.aspect.HttpAspect - 接口参数=TestParam(code=11, desc=123)
2020-04-13 21:03:47.227 [http-nio-9905-exec-1] INFO
2020-04-13 21:03:47.235 [http-nio-9905-exec-1] INFO com.cb.springboottest.aspect.HttpAspect - 执行 com.cb.springboottest.controller.BIllController.getBill 耗时为:10ms
2020-04-13 21:03:47.311 [http-nio-9905-exec-1] INFO com.cb.springboottest.aspect.HttpAspect - 接口响应={"code":"200","desc":"操作成功!","message":{"appCipher":"333","appId":"11","createBy":"我是数据库test2","created":"2020-04-04 22:35:33.0","id":1,"updated":"2020-04-04 22:35:33.0"}}