Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save AlexanderWert/77bb94421a5ee7b64748c79f0a3f369c to your computer and use it in GitHub Desktop.
Save AlexanderWert/77bb94421a5ee7b64748c79f0a3f369c to your computer and use it in GitHub Desktop.
Elastic APM Java agent - Custom metrics in plugins
package co.elastic.apm.example.webserver.plugin;
import co.elastic.apm.agent.sdk.ElasticApmInstrumentation;
import io.micrometer.core.instrument.Metrics;
import io.micrometer.core.instrument.simple.SimpleMeterRegistry;
import net.bytebuddy.asm.Advice;
import net.bytebuddy.description.method.MethodDescription;
import net.bytebuddy.description.type.TypeDescription;
import net.bytebuddy.matcher.ElementMatcher;
import java.util.Collection;
import java.util.Collections;
import static net.bytebuddy.matcher.ElementMatchers.named;
import static net.bytebuddy.matcher.ElementMatchers.takesArgument;
import static net.bytebuddy.matcher.ElementMatchers.takesArguments;
public class ExampleMetricsInstrumentation extends ElasticApmInstrumentation {
//For detailed documentation of these 3 methods, see the
// package adjacent ExampleHttpServerInstrumentation class
@Override
public ElementMatcher<? super TypeDescription> getTypeMatcher() {
return named("org.test.MyClass");
}
@Override
public ElementMatcher<? super MethodDescription> getMethodMatcher() {
return named("myMethod");
}
@Override
public Collection<String> getInstrumentationGroupNames() {
return Collections.singletonList("elastic-plugin-example");
}
public static class AdviceClass {
private static volatile boolean metricWasAdded = false;
@Advice.OnMethodEnter(suppress = Throwable.class, inline = false)
public static void onEnterHandle() {
if (!metricWasAdded) {
Metrics.addRegistry(new SimpleMeterRegistry(new SimpleConfig() {
@Override
public CountingMode mode() {
// to report the delta since the last report
// this makes building dashboards a bit easier
return CountingMode.STEP;
}
@Override
public Duration step() {
// the duration should match metrics_interval, which defaults to 30s
return Duration.ofSeconds(30);
}
@Override
public String get(String key) {
return null;
}
}, Clock.SYSTEM));
metricWasAdded = true;
}
Metrics.counter("page_counter").increment();
}
}
}
...
<dependencies>
...
<dependency>
<groupId>io.micrometer</groupId>
<artifactId>micrometer-core</artifactId>
<version>1.9.0</version>
<exclusions>
<exclusion>
<groupId>org.hdrhistogram</groupId>
<artifactId>HdrHistogram</artifactId>
</exclusion>
</exclusions>
</dependency>
...
</dependencies>
...
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment