前言
我们在日常开发中,项目里日志是必不可少的,一般有业务日志,数据库日志,异常日志等,主要用于帮助程序猿后期排查一些生产中的bug。
有时候程序猿们在做代码调优的时候需要关注每个接口的响应速度,所以需要打印接口调用时间,如果在接口中每次写这段代码实在恶心,故基于Spring AOP面向切面编程使用注解解决该问题。
1.定义注解
value为对应的接口名称,默认为BaseController
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface OwnLog {
String value() default "BaseController";
}
2.面向切面处理
@Aspect
@Component
@Slf4j
public class LogAspect {
@Before(value = "@annotation(ownLog)")
public void before(JoinPoint point, OwnLog ownLog) {
//point.getArgs()获取请求参数
log.info("服务{}调用开始,请求参数:{}", ownLog.value(), JSONObject.toJSONString(point.getArgs()));
}
@Around(value = "@annotation(ownLog)")
public Object around(ProceedingJoinPoint point, OwnLog ownLog) {
Object result = null;
String name = ownLog.value();
long start = System.currentTimeMillis();
try {
result = point.proceed();
} catch (Throwable throwable) {
throwable.printStackTrace();
} finally {
long end = System.currentTimeMillis();
log.info(String.format("服务%s,耗时:%dms", name, (end - start)));
}
return result;
}
//设置rvt为返回参数
@AfterReturning(value = "@annotation(ownLog)", returning = "rvt")
public void afterReturning(JoinPoint point, OwnLog ownLog, Object rvt) {
log.info("服务{}调用结束,response:{}", ownLog.value(), JSONObject.toJSONString(rvt));
}
}
3.使用注解
@OwnLog("sendMsg")
@Idempotent
@ApiOperation(value = "消息推送")
@PostMapping(value = "/sendMsg")
public BaseResp sendMessage(@ModelAttribute UserMsgHistoryDTO userMsgHistoryDTO) {
userMsgHistoryService.sendMessage(findCurrentUser(), userMsgHistoryDTO);
addUserLog(LOG_TYPE_USER, "用户消息推送", JSON.toJSONString(userMsgHistoryDTO));
return new BaseResp<>(ResultStatus.SUCCESS);
}
4.控台打印
服务addEnrolmentUser调用开始,request:[{"age":0,"country":"string","health":"一般","idNum":"12345","name":"string","phoneNum":"string","status":"审核中"}]
服务addEnrolmentUser,耗时:13ms
服务addEnrolmentUser调用结束,response:{"code":10000,"message":"操作成功","success":true}