Skip to content

Instantly share code, notes, and snippets.

@hirokazumiyaji
Last active August 23, 2017 08:53
Show Gist options
  • Save hirokazumiyaji/31ce8b47855170d31c3be2de1f0c2ff4 to your computer and use it in GitHub Desktop.
Save hirokazumiyaji/31ce8b47855170d31c3be2de1f0c2ff4 to your computer and use it in GitHub Desktop.
package com.github.gist.hirokazumiyaji;
import java.util.concurrent.TimeUnit;
import io.micrometer.core.instrument.Timer;
import io.micrometer.spring.web.MeterRegistry;
import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;
public final class OkHttpMetricsInterceptor implements Interceptor {
private final MeterRegistry registry;
private final OkHttpTagConfigurer tagConfigurer;
private final String metricsName;
public OkHttpMetricsInterceptor(MeterRegistry registry, OkHttpTagConfigurer tagConfigurer, String metricsName) {
this.registry = registry;
this.tagConfigurer = tagConfigurer;
this.metricsName = metricsName;
}
@Override
public Response intercept(Interceptor.Chain chain) throws IOException {
final Request request = chain.request();
final long startTime = System.nanoTime();
final Response response = chain.proceed(request);
final long endTime = System.nanoTime();
Timer.Builder timerBuilder = registry.timerBuilder(metricsName)
.tags(tagConfigurer.requestTags(request, response));
timerBuilder.create().record(endTime - startTime, TimeUnit.NANOSECONDS);
return response;
}
}
package com.github.gist.hirokazumiyaji;
import io.micrometer.core.instrument.Tag;
import okhttp3.Request;
import okhttp3.Response;
public class OkHttpTagConfigurer {
public Iterable<Tag> requestTags(Request request, Response response) {
return asList(method(request), uri(request), status(response));
}
public Tag method(Request request) {
return Tag.of("method", request.method());
}
public Tag uri(Request request) {
return Tag.of("uri", request.url().toString());
}
public Tag status(Response response) {
return Tag.of("status", String.valueOf(response.code()));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment