Last active
August 23, 2017 08:53
-
-
Save hirokazumiyaji/31ce8b47855170d31c3be2de1f0c2ff4 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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