Skip to content

Instantly share code, notes, and snippets.

@fastnsilver
Last active December 15, 2023 15:52
Show Gist options
  • Save fastnsilver/15f4fee29bf324d6d7d0 to your computer and use it in GitHub Desktop.
Save fastnsilver/15f4fee29bf324d6d7d0 to your computer and use it in GitHub Desktop.
How to configure AWS CloudWatch metrics w/ Spring Boot
// Modeled after {@link org.springframework.cloud.netflix.servo.ServoMetricCollector}
// employed explicitly for publication of AWS CloudWatch metrics
public class CloudWatchMetricCollector {
private final Logger log = LoggerFactory.getLogger(getClass());
@Value("${spring.aws.cloudwatch.metrics.polling.timeUnit:SECONDS}")
private String timeUnit;
@Value("${spring.aws.cloudwatch.metrics.polling.interval:5}")
private int pollingInterval;
@Value("${spring.application.name}")
private String applicationName;
@Autowired
private AWSCredentials awsCredentials;
public CloudWatchMetricCollector() {
List<MetricObserver> observers = new ArrayList<MetricObserver>();
observers.add(new CloudWatchMetricObserver(applicationName, "servo.cloudwatch", new AmazonCloudWatchAsyncClient(awsCredentials)));
PollRunnable task = new PollRunnable(new MonitorRegistryMetricPoller(),
BasicMetricFilter.MATCH_ALL, true, observers);
if (!PollScheduler.getInstance().isStarted()) {
try {
PollScheduler.getInstance().start();
}
catch (Exception e) {
// Can fail due to race condition with evil singletons (if more than one
// app in same JVM)
log.error("Could not start AWS CloudWatch metrics poller", e);
return;
}
}
PollScheduler.getInstance().addPoller(task, pollingInterval, TimeUnit.valueOf(timeUnit));
}
@PreDestroy
public void destroy() throws Exception {
log.info("Stopping Servo PollScheduler");
if (PollScheduler.getInstance().isStarted()) {
try {
PollScheduler.getInstance().stop();
}
catch (Exception e) {
log.error("Could not stop servo metrics poller", e);
}
}
}
}
@Configuration
@ConditionalOnAwsCloudEnvironment
@EnableContextCredentials
public class CloudWatchMetricsConfig {
@Bean
public CloudWatchMetricCollector cloudWatchMetricCollector() {
return new CloudWatchMetricCollector();
}
}
@fastnsilver
Copy link
Author

If you want to use above config you have to disable ServoMetricsAutoConfiguration, using exclude attribute of EnableAutoConfiguration annotation. To have the above plus what Spring Cloud provides opt for declaring MetricObserver impls as beans, scan for them, then create another collector that adds these to list in constructor as above. Going to post alt impl soon as it's preferable to have a unified extensible impl.

@fastnsilver
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment