1. 程式人生 > >springBoot記錄Http訪問日誌(簡單入門2)

springBoot記錄Http訪問日誌(簡單入門2)

一.記錄請求資訊
@Aspect
@Component
public class HttpAspect {

    private static final Logger logger  = LoggerFactory.getLogger(HttpAspect.class);

    /**
     * 這樣寫是將重複的程式碼提取出來方便處理
     */
    @Pointcut("execution(public * com.kafei.HelloController.*(..))")
    public void log() {}

    /**
     *
     * @param joinPoint
     * 注意:該方法中的HttpServletRequest為javax.servlet.http.HttpServletRequest;
*/ @Before("log()") public void doBefore(JoinPoint joinPoint) { logger.info("1"); ServletRequestAttributes attributes = (ServletRequestAttributes)RequestContextHolder.getRequestAttributes(); HttpServletRequest request = attributes.getRequest(); //記錄請求路徑url logger.info("url={}",request.getRequestURL()); //記錄請求方式method logger.info("method={}",request.getMethod()); //記錄訪問者ip logger.info("ip={}",request.getRemoteAddr()); //記錄訪問的類方法 logger.info("class_method={}",joinPoint.getSignature().getDeclaringTypeName()+"."+joinPoint.getSignature().getName()); //記錄傳遞的引數 logger.info("args={}",joinPoint.getArgs()); } @After("log()") public void doAfter() { logger.info("2"); } @AfterReturning(returning = "obj",pointcut = "log()") public void doAfterReturning(Object obj) { logger.info("3"); logger.info("response={}",obj); } }
二.請求地址:http://127.0.0.1:8080/aa?id=100
三.HelloController.java
@RestController
public class HelloController {

    @GetMapping("/aa")
    public String aa(Girl girl) {
        System.out.println("aa");
        return "aa2";
    }

}

四.結果
2018-05-28 11:19:51.976  INFO 6084 --- [nio-8080-exec-1] com.kafei.aspect.HttpAspect              : 1
2018-05-28 11:19:51.977  INFO 6084 --- [nio-8080-exec-1] com.kafei.aspect.HttpAspect              : url=http://127.0.0.1:8080/aa
2018-05-28 11:19:51.978  INFO 6084 --- [nio-8080-exec-1] com.kafei.aspect.HttpAspect              : method=GET
2018-05-28 11:19:51.978  INFO 6084 --- [nio-8080-exec-1] com.kafei.aspect.HttpAspect              : ip=127.0.0.1
2018-05-28 11:19:51.980  INFO 6084 --- [nio-8080-exec-1] com.kafei.aspect.HttpAspect              : class_method=com.kafei.HelloController.aa
2018-05-28 11:19:51.980  INFO 6084 --- [nio-8080-exec-1] com.kafei.aspect.HttpAspect              : args=Girl{id=100, age=null}
aa
2018-05-28 11:19:51.985  INFO 6084 --- [nio-8080-exec-1] com.kafei.aspect.HttpAspect              : 2
2018-05-28 11:19:51.985  INFO 6084 --- [nio-8080-exec-1] com.kafei.aspect.HttpAspect              : 3
2018-05-28 11:19:51.985  INFO 6084 --- [nio-8080-exec-1] com.kafei.aspect.HttpAspect              : response=aa2
五.總結

1.方法執行順序:@Before>aa()>@After>@AfterReturning

2.logger.info("url={}",request.getRequestURL());,這裡{}理解為變數,request.getRequestURL()理解為該變數的值