All Downloads are FREE. Search and download functionalities are using the official Maven repository.

tech.mhuang.pacebox.springboot.autoconfiguration.trace.okhttp.TraceOkHttpInterceptor Maven / Gradle / Ivy

There is a newer version: 2023.0.0.0
Show newest version
package tech.mhuang.pacebox.springboot.autoconfiguration.trace.okhttp;

import com.alibaba.fastjson2.JSON;
import io.micrometer.tracing.Span;
import io.micrometer.tracing.Tracer;
import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;

import java.io.IOException;
import java.util.regex.Pattern;

/**
 * okhttp埋点拦截
 *
 * @author mhuang
 * @since 1.0.0
 */
public class TraceOkHttpInterceptor implements Interceptor {

    private static final String COMPONENT_NAME = "okhttp";
    private final Tracer tracer;
    private Pattern skipPattern;

    public TraceOkHttpInterceptor(Tracer tracer) {
        this.tracer = tracer;
    }

    public TraceOkHttpInterceptor(Tracer tracer, Pattern skipPattern) {
        this.tracer = tracer;
        this.skipPattern = skipPattern;
    }

    protected boolean isTraced(Request request) {
        if (skipPattern != null) {
            String url = request.url().toString();
            return skipPattern.matcher(url).matches();
        }

        return false;
    }

    @Override
    public Response intercept(Chain chain) throws IOException {
        Request request = chain.request();
        if (isTraced(request)) {
            return chain.proceed(request);
        }
        Span span = tracer.nextSpan().name(COMPONENT_NAME).tag("request.method", request.method());
        span.tag("request.header", JSON.toJSONString(request.headers()));
        span.tag("request.body", JSON.toJSONString(request.body()));
        span.tag("request.url", request.url().toString());
        span.tag("request.param", request.url().query());
        try (Tracer.SpanInScope ignored = this.tracer.withSpan(span.start())) {
            Response response = chain.proceed(request);
            span.tag("http.status", String.valueOf(response.code()));
            span.tag("result", JSON.toJSONString(response.body()));
            span.event("okhttpEnd");
            return response;
        } catch (IOException e) {
            span.error(e);
            throw new IOException(e);
        } finally {
            span.end();
        }
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy