1. 程式人生 > >AOP記錄Controller日誌

AOP記錄Controller日誌


@Aspect
@Component
@Slf4j
public class ReqResAop {
    @Pointcut("@annotation(org.springframework.web.bind.annotation.RequestMapping)" +
            "||@annotation(org.springframework.web.bind.annotation.GetMapping)" +
            "||@annotation(org.springframework.web.bind.annotation.PostMapping)"
+ "||@annotation(org.springframework.web.bind.annotation.PutMapping)" + "||@annotation(org.springframework.web.bind.annotation.DeleteMapping)") public void performance() { } @Around("performance()") public Object doAround(ProceedingJoinPoint proceedingJoinPoint)
throws Throwable { long start = System.currentTimeMillis(); RequestAttributes ra = RequestContextHolder.getRequestAttributes(); ServletRequestAttributes sra = (ServletRequestAttributes) ra; HttpServletRequest request = sra.getRequest(); String url = request.
getRequestURI(); Object[] objects = proceedingJoinPoint.getArgs(); Object result = null; try { String reqStr = JsonUtils.obj2Json(objects); result = proceedingJoinPoint.proceed();// result的值就是被攔截方法的返回值 String resStr = JsonUtils.obj2Json(result); long end = System.currentTimeMillis(); log.info("\n===============請求===============\n" + "url:{}\n" + "{}\n" + "===============響應===============\n" + "{}\n" + "=============耗時:{} 毫秒============================" , url, reqStr, resStr, (end - start)); log.info("===============END==============="); } catch (Exception e) { log.error(e.getMessage(), e); //這裡不丟擲異常的話,RestControllerAdvice就攔截不到了,因為此處捕獲了 throw new RuntimeException(e.getMessage()); } return result; } }