Java agent set environment programatically

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

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

I created elasticapm.properties 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).

Hi,
thanks for your reply.

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

    @Profile({"dev", "stage", "prod"})
    @Component
    @Order(Ordered.HIGHEST_PRECEDENCE)
    @Log4j2
    public class ApmConfig {

        @Autowired
        private Environment environment;

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

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.