SpringBoot服务添加自定义注解增加接口日志切面功能

  • 1.日志切面注解定义
@Target(ElementType.METHOD) //注解放置的目标位置,METHOD是可注解在方法级别上
@Retention(RetentionPolicy.RUNTIME) //注解在哪个阶段执行
@Documented
public @interface SysLog {
String value() default "";
}
  • 2.日志切面类
@Aspect
@Component
@Slf4j
public class AspectLog {

ThreadLocal<Long> startTime = new ThreadLocal<Long>();

@Pointcut("@annotation(com.jysp.core.annotation.SysLog)")
public void logPointCut() {
}

@Before(value = "logPointCut()")
public void methodBefore(JoinPoint joinPoint) {
//开始时间
startTime.set(System.currentTimeMillis());
ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
HttpServletRequest request = requestAttributes.getRequest();
//打印请求内容
log.info("===============请求内容===============");
log.info("请求地址:" + request.getRequestURL().toString());
log.info("请求方式:" + request.getMethod());
log.info("请求类方法:" + joinPoint.getSignature());
String args = joinPoint.getArgs() != null ? Arrays.toString(joinPoint.getArgs()) : "";
log.info("请求类方法参数:" + args);
log.info("=======================================");
}

@AfterReturning(returning = "o", pointcut = "logPointCut()")
public void methodAfterReturning(Object o) {
//打印返回内容
log.info("--------------返回内容----------------");
String responseContent = o != null ? JSON.toJSONString(o) : "";
log.info("Response内容:" + responseContent);
//打印响应时间
log.info("--------------响应时间----------------");
log.info("请求处理时间为:" + (System.currentTimeMillis() - startTime.get()) + "毫秒");
log.info("=======================================");
}
}
  • 3.接口方法上增加注解
  @SysLog
  @PostMapping("/test")
  public ResponseBean<String> test(@RequestBody Test dto) {
  }
posted @ 2022-04-02 10:51  _最初  阅读(259)  评论(0编辑  收藏  举报