使用Spring的AOP實現切面日誌

AOP切面日誌的使用方式java

@Aspect
@Component
public class HttpAspect {

    private static final Logger logger = LoggerFactory.getLogger(HttpAspect.class);
    //定義切點
    @Pointcut("execution(public * com.example.springdemo.controller.*.*(..))")
    public void log() {
    }

    @Before("log()")
    public void doBefore(JoinPoint joinPoint) {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();

        StringBuilder httpInfo = new StringBuilder();

        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        // 請求的方法參數值
        Object[] args = joinPoint.getArgs();
        // 請求的方法參數名稱
        LocalVariableTableParameterNameDiscoverer u = new LocalVariableTableParameterNameDiscoverer();
        String[] paramNames = u.getParameterNames(method);
        String params = "";
        if (args != null && paramNames != null) {
            for (int i = 0; i < args.length; i++) {
                params += " " + paramNames[i] + ": " + args[i];
            }
        }
        //拼接參數請求報文
        httpInfo.append("[{DATE=").append(DateUtils.convertDateTimeToString(new Date())).append("},{URI=").append(request.getRequestURI()).append("},{method=").append(request.getMethod())
                .append("},{ip=").append(request.getRemoteAddr()).append("},{params=");

        if (!StringUtils.isEmpty(params)) {
            httpInfo.append(JsonUtils.objectToJson(params));
        }
        httpInfo.append("}]");
        logger.info("request = {}", httpInfo);

    }

    @After("log()")
    public void doAfter() {
    }

    /**
     * 記錄請求完成以後的響應體
     *
     * @param object
     */
    @AfterReturning(returning = "object", pointcut = "log()")
    public void doAfterReturning(Object object) {
        logger.info("response={}", JsonUtils.objectToJson(object));
    }
}
相關文章
相關標籤/搜索