1. 程式人生 > 其它 >SpringBoot服務新增自定義註解增加介面日誌切面功能

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) {
  }