Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save eyalkoren/46ef4a262483ea4ef4fc733eb6043e61 to your computer and use it in GitHub Desktop.
Save eyalkoren/46ef4a262483ea4ef4fc733eb6043e61 to your computer and use it in GitHub Desktop.
Monitoring Elasticsearch Java REST Client by Elastic APM Java Agent - demo
public class ElasticsearchRestClientInstrumentation extends ElasticApmInstrumentation {
private static class ElasticsearchRestClientAdvice {
@Advice.OnMethodEnter(suppress = Throwable.class)
private static void onBeforeExecute(@Advice.Argument(0) Request request,
@Advice.Local("span") Span span) {
span = tracer.getActive().createSpan()
.withType("db").withSubtype("elasticsearch").withAction("request")
.appendToName("Elasticsearch: ").appendToName(request.getMethod())
.appendToName(" ").appendToName(request.getEndpoint());
span.getContext().getDb().withType("elasticsearch");
span.activate();
span.getContext().getHttp().withMethod(request.getMethod());
if (request.getEndpoint().endsWith("_search")) {
HttpEntity entity = request.getEntity();
if (entity != null && entity.isRepeatable()) {
IOUtils.readUtf8Stream(entity.getContent(),
span.getContext().getDb().withStatementBuffer());
}
}
}
@Advice.OnMethodExit(suppress = Throwable.class, onThrowable = Throwable.class)
public static void onAfterExecute(@Advice.Return @Nullable Response response,
@Advice.Local("span") @Nullable Span span,
@Advice.Thrown @Nullable Throwable t) {
try {
String url = null; int statusCode = -1;
if (response != null) {
url = response.getHost().toURI();
statusCode = response.getStatusLine().getStatusCode();
} else if (t != null) {
if (t instanceof ResponseException) {
ResponseException esre = (ResponseException) t;
url = esre.getResponse().getHost().toURI();
statusCode = esre.getResponse().getStatusLine().getStatusCode();
}
span.captureException(t);}
span.getContext().getHttp().withUrl(url);
span.getContext().getHttp().withStatusCode(statusCode);
} finally {
span.deactivate().end();
}
}
}
public Class<?> getAdviceClass() {
return ElasticsearchRestClientAdvice.class;
}
public ElementMatcher<? super TypeDescription> getTypeMatcher() {
return named("org.elasticsearch.client.RestClient");
}
public ElementMatcher<? super MethodDescription> getMethodMatcher() {
return named("performRequest").and(takesArguments(1)
.and(takesArgument(0, named("org.elasticsearch.client.Request"))));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment