Programmatic API setup to self-attachedit

Note

This installation method is experimental.

Supported environmentsedit

The attachment is supported on Windows, Unix and Solaris operating systems on HotSpot-based JVMs (like OpenJDK and Oracle JDK) and OpenJ9.

Some flags, like --include and --exclude require the jps command to be installed, which is part of the JDK distribution and does not typically come with the JRE distribution.

Caveatsedit

Currently, this does not work in combination with OSGi containers (which includes most application servers). The symptom is that there will be a lot of exceptions like this: java.lang.NoClassDefFoundError: co/elastic/apm/agent/servlet/ServletApiAdvice.

There can only be one agent instance with one configuration per JVM. So if you deploy multiple web applications to the same application server and call ElasticApmAttacher.attach() in each application, the first attach() wins and the second one will be ignored. That also means that if you are configuring the agent with elasticapm.properties, the application which attaches first gets to decide the configuration. See the default value description of the service_name configuration option for ways to have different `service.name`s for each deployment.

Usageedit

Declare a dependency to the apm-agent-attach artifact.

pom.xml. 

<dependency>
    <groupId>co.elastic.apm</groupId>
    <artifactId>apm-agent-attach</artifactId>
    <version>${elastic-apm.version}</version>
</dependency>

Call ElasticApmAttacher.attach() in the first line of your public static void main(String[] args) method.

This example demonstrates the the usage of the attach API with a simple Spring Boot application:

MyApplication.java. 

import co.elastic.apm.attach.ElasticApmAttacher;
import org.springframework.boot.SpringApplication;

@SpringBootApplication
public class MyApplication {
    public static void main(String[] args) {
        ElasticApmAttacher.attach();
        SpringApplication.run(MyApplication.class, args);
    }
}

Note

The API is not limited to Spring Boot and does not require Spring Boot, it is just used for demonstration purposes.

Configurationedit

The recommended way of configuring the agent when using the attach API is to add the configuration to src/main/resources/elasticapm.properties.