Okhttp3自定义日志拦截器


import java.util.HashMap;
import java.util.Map;

public enum Level {
    /**
     * No logs.
     */
    NONE,
    /**
     * --> currentTime , method, uri , userId , sessionId ,stackTrace
     * <-- currentTime, httpStatus, method, uri
     */
    INFO,

    /**
     * --> currentTime , method , uri , userId , sessionId , headers , body ,stackTrace
     * <-- currentTime , httpStatus , method , uri , headers , body
     */
    DEBUG;

    static Map<String, Level> map = new HashMap<>() {
        private static final long serialVersionUID = -2873590923344392083L;

        {
            put("NONE",NONE);
            put("INFO",INFO);
            put("DEBUG",DEBUG);
        }
    };

    public static Level nameOf(String name) {
        return map.get(name);
    }
}

 

 

import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.ObjectUtil;
import com.aiis.meeting.common.util.OkHttpUtil;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import okio.Buffer;
import okio.BufferedSource;
import org.jetbrains.annotations.NotNull;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.TimeUnit;


@Slf4j
public class CustomHttpLoggingInterceptor implements Interceptor {

    private Level level;

    public CustomHttpLoggingInterceptor(Level level) {
        this.level = level;
    }

    @NotNull
    @Override
    public Response intercept(@NotNull Chain chain) throws IOException {
        OkHttpUtil.Tuple tuple = OkHttpUtil.getLocalAndRemove();
        String traceId = getUUID();

        if (ObjectUtil.isNull(tuple)) {
            if (Level.NONE.equals(level)) {
                return logNone(chain, tuple);
            }
            if (Level.INFO.equals(level)) {
                return logInfo(chain, tuple, traceId);
            }
            if (Level.DEBUG.equals(level)) {
                return logDebug(chain, tuple, traceId);
            }
        }
    
        Level level = tuple.getLevel();
        if (Level.NONE.equals(level)) {
            return logNone(chain, tuple);
        }

        if (Level.INFO.equals(level)) {
            return logInfo(chain, tuple, traceId);
        }

        return logDebug(chain, tuple, traceId);
    }
    
    private Response logNone(Chain chain, OkHttpUtil.Tuple tuple) throws IOException {
        return chain.proceed(chain.request());
    }
    
    private Response logInfo(Chain chain, OkHttpUtil.Tuple tuple, String traceId) throws IOException {
        Request request = chain.request();
        String method = request.method();
        String uri = request.url().uri().toString();

        print(String.format("%s -->  %s %s userId:%s stackTrace:%s", traceId, method, uri, tuple.getUserId(), tuple.getStackTrace()));

        long startNs = System.nanoTime();
        Response response = chain.proceed(request);
        long timeMillis = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startNs);
        int code = response.code();
        boolean successful = response.isSuccessful();

        if (ObjectUtil.isNull(tuple)) {
            logWithoutContext(successful, response, traceId);
        }
        
        if (ObjectUtil.isNotNull(tuple)) {
            if (successful) {
                print(String.format("%s <-- %s %sms", traceId, code, timeMillis));
            }
            if (!successful) {
                print(String.format("%s <-- %s %s", traceId, code, getBodyCopy(response)));
            }
        }

        return response;
    }
    
     private Response logDebug(Chain chain, OkHttpUtil.Tuple tuple, String traceId) throws IOException {
        Request request = chain.request();
        String method = request.method();
        String uri = request.url().uri().toString();
        RequestBody body = request.body();

        print(String.format("%s --> %s %s userId:%s stackTrace:%s", traceId, method, uri, tuple.getUserId(), tuple.getStackTrace()));
        logRequestHeaders(request, traceId);

        String bodyStr = null;
        long bodyLength = 0;
        String mediaType = null;
        if (body != null) {
        bodyLength = body.contentLength();
            if (bodyLength > 0) {
                mediaType = body.contentType().toString();
                Buffer buffer = new Buffer();
                body.writeTo(buffer);
                bodyStr = buffer.readString(StandardCharsets.UTF_8);
            }
        }

        if (body != null) {
            print(String.format("%s --> Content-Type %s Content-Length %s", traceId, mediaType, bodyLength));
            print(String.format("%s --> request body%n%s", traceId, bodyStr));
        }

        long startNs = System.nanoTime();
        Response response = chain.proceed(request);
        long timeMillis = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startNs);
        boolean successful = response.isSuccessful();
        if (ObjectUtil.isNull(tuple)) {
            logWithoutContext(successful, response, traceId);
        }
        
        if (ObjectUtil.isNotNull(tuple)) {
            if (successful) {
                logResponseHeaders(response, traceId);
            }
            print(String.format("%s <-- %s %sms %n%s", traceId, response.code(), timeMillis, getBodyCopy(response)));
        }

        return response;
    }
    
    private void logWithoutContext(boolean successful, Response response, String traceId) throws IOException {
        if (successful) {
            print(String.format("%s <-- %s", traceId, response.code()));
        }
        if (!successful) {
            print(String.format("%s <-- %s %n%s", traceId, response.code(), getBodyCopy(response)));
        }
    }
    
    private void logRequestHeaders(Request request, String traceId) {
        Headers headers = request.headers();
        for (int i = 0; i < headers.size(); i++) {
            print(String.format("%s --> header %s %s", traceId, headers.name(i), headers.value(i)));
        }
    }
    
    private void logResponseHeaders(Response response, String traceId) {
        Headers headers = response.headers();
        for (int i = 0; i < headers.size(); i++) {
            print(String.format("%s <-- header %s %s", traceId, headers.name(i), headers.value(i)));
        }
    }
    
    private String getBodyCopy(Response response) throws IOException {
        BufferedSource source = response.body().source();
        source.request(Long.MAX_VALUE);
        return source.getBuffer().clone().readString(StandardCharsets.UTF_8);
    }

    public void setLevel(Level level) {
        this.level = level;
    }

    private static String getUUID() {
        return UUID.fastUUID().toString().replaceAll("-", "");
    }

    private void print(String str) {
        log.info(str);
    }
}

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM