1. 程式人生 > >SpringBoot AOP 記錄WEB請求日誌

SpringBoot AOP 記錄WEB請求日誌

實現AOP的切面主要有以下幾個要素:

使用@Aspect註解將一個java類定義為切面類
使用@Pointcut定義一個切入點,可以是一個規則表示式,比如下例中某個package下的所有函式,也可以是一個註解等。
根據需要在切入點不同位置的切入內容
使用@Before在切入點開始處切入內容
使用@After在切入點結尾處切入內容
使用@AfterReturning在切入點return內容之後切入內容(可以用來對處理返回值做一些加工處理)
使用@Around在切入點前後切入內容,並自己控制何時執行切入點自身的內容
使用@AfterThrowing用來處理當切入內容部分丟擲異常之後的處理邏輯

下面附上程式碼,我覺得真沒有必要囉嗦的去解釋了,看一下就明瞭

package com.shanhy.sboot.aoplog;

import java.util.Arrays;

import javax.servlet.http.HttpServletRequest;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation
.Around; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Before; import org.aspectj.lang.annotation.Pointcut; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Component; import org.springframework.web.context.request.RequestContextHolder
; import org.springframework.web.context.request.ServletRequestAttributes; @Aspect @Component public class WebLogAspect { private static final Logger LOG = LoggerFactory.getLogger(WebLogAspect.class); @Pointcut("execution(public * com.shanhy.sboot..controller.*.*(..))")//兩個..代表所有子目錄,最後括號裡的兩個..代表所有引數 public void logPointCut() { } @Before("logPointCut()") public void doBefore(JoinPoint joinPoint) throws Throwable { // 接收到請求,記錄請求內容 ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes(); HttpServletRequest request = attributes.getRequest(); // 記錄下請求內容 LOG.info("請求地址 : " + request.getRequestURL().toString()); LOG.info("HTTP METHOD : " + request.getMethod()); LOG.info("IP : " + request.getRemoteAddr()); LOG.info("CLASS_METHOD : " + joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName()); LOG.info("引數 : " + Arrays.toString(joinPoint.getArgs())); } @AfterReturning(returning = "ret", pointcut = "logPointCut()")// returning的值和doAfterReturning的引數名一致 public void doAfterReturning(Object ret) throws Throwable { // 處理完請求,返回內容 LOG.info("返回值 : " + ret); } @Around("logPointCut()") public Object doAround(ProceedingJoinPoint pjp) throws Throwable { long startTime = System.currentTimeMillis(); Object ob = pjp.proceed();// ob 為方法的返回值 LOG.info("耗時 : " + (System.currentTimeMillis() - startTime)); return ob; } }
package com.shanhy.sboot.demo.controller;

import java.util.concurrent.TimeUnit;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/log")
public class WebLogTestController {

    @RequestMapping("/test")
    public String test() {
        try {
            TimeUnit.SECONDS.sleep(5);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return "TEST";
    }

}

結束。