【代码】Hutool工具增加拦截器打印请求和响应和配置

show me the code:


import cn.hutool.http.GlobalInterceptor;
import cn.hutool.http.HttpGlobalConfig;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Random;

/**
 * @Description
 * @Date 2023/10/13
 * @Version 1.0
 **/
@Slf4j
@Component
public class hutoolHttpUtilConfig {
    Logger logger = LoggerFactory.getLogger(HttpGlobalConfig.class);
    Double id ;
    @Autowired
    public void hutoolHttpUtilConfig() {
        // 设置hutool HttpUtil的request请求参数打印
//        GlobalInterceptor.INSTANCE.addRequestInterceptor(httpObj -> log.info(String.valueOf(httpObj)));

        GlobalInterceptor.INSTANCE.addRequestInterceptor(httpObj -> this.wirteRequestLog(httpObj));

        // 设置hutool HttpUtil的response参数打印
//        GlobalInterceptor.INSTANCE.addResponseInterceptor(httpObj -> log.info(String.valueOf(httpObj)));
        GlobalInterceptor.INSTANCE.addResponseInterceptor(httpObj -> this.writeResponseLog(httpObj));

        // 设置hutool HttpUtil的连接超时时间、读取响应超时时间
        HttpGlobalConfig.setTimeout(3000);
    }

    private Double wirteRequestLog(HttpRequest request){
        System.out.println(request);
        id = Math.random();
        System.out.println("request随机数" + id);
        return id;
    }

    private void writeResponseLog(HttpResponse response){
        System.out.println(response);
        System.out.println("response随机数" + id);
    }

}

下面额外记录使用aop来获取日志


import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

/**
 * @Description 记录调用第三方日志
 * @Date 2023/10/12
 * @Version 1.0
 **/
@Aspect
@Order(0)
@Component
public class AOPForAccessLog {
    @Pointcut("execution(* com.*.aiops.*.proxy.third.*.*.*(..))")
    public void thirdPartyMethod() {}


    @Before("thirdPartyMethod()")
    public void methodBefore(JoinPoint joinPoint) {
        Object[] args = joinPoint.getArgs();
        System.out.println("Method: " + joinPoint.getSignature().getName());
        for (Object arg : args) {
            System.out.println("Request Parameter: " + arg);
        }
    }

//    @After(pointcut = "thirdPartyMethod() && executeMethod()", returning = "response")
    @AfterReturning(pointcut = "thirdPartyMethod() ", returning = "response")
    public void methodAfter(JoinPoint joinPoint, Object response) {
        System.out.println("Method: " + joinPoint.getSignature().getName());
        System.out.println("Response: " + response);
    }
}

你可能感兴趣的:(java,spring,mybatis)