Java agent set environment programatically

I'm attaching APM agent in my Spring Boot application like this:

public class MyApplication {
    public static void main(String[] args) {
        ElasticApmAttacher.attach();, args);

I created file in my resource folder and everything works fine.
However I'd like to se the environment property in the file programatically because I run the application with different Spring profile and I want APM add the right environment to logs.

I tried to pass a Map<String,String> to attach() method but it seems in this way values set in my property file is not read.

Do you have any suggestion? Thanks

Hi @Daniele_Renda,

You are initializing the agent using the Programatic API, which has some limitations when combined with other ways to provide configuration.

As explained in our configuration page in documentation, configuration sources for (5) are mutually exclusive, and in your case you are trying to mix items in (b) and (c).

thanks for your reply.

I ended up to do this with Spring, what do you think about?

    @Profile({"dev", "stage", "prod"})
    public class ApmConfig {

        private Environment environment;

        public void init() {
  "Starting APM Java agent...");
            Map<String, String> propertyMap = new HashMap<>();
            try {
                final Properties props = new Properties();
                try (InputStream resourceStream = ElasticApmAttacher.class.getClassLoader().getResourceAsStream("")) {
                    if (resourceStream != null) {
                        for (String propertyName : props.stringPropertyNames()) {
                            propertyMap.put(propertyName, props.getProperty(propertyName));
                } catch (IOException e) {
                //Add environment value
                propertyMap.put("environment", System.getProperty(""));
            } catch (Exception e) {
                log.error("", e);

That should work, you could even use the fact that Properties is in fact a map and avoid copy everything (will require a cast).

This topic was automatically closed 20 days after the last reply. New replies are no longer allowed.